[英]Swift - Using custom classes as cells in a TableView
我正在嘗試使用Swift在TableView中顯示電影列表。 電影對象基本上具有標題,等級,流派等。
這是Movie.swift類
class Movie {
enum Genre { case scifi, romance, thriller, drama }
var title: String
var genre: Genre
var rating: Int
init(title: String, genre: Genre, rating: Int){
self.title = title
self.genre = genre
self.rating = rating
}
在我的ViewController.swift代碼中,我擁有這個來保存Movie對象的列表
var movies = [
Movie(title: "Citizen Kane", genre: Movie.Genre.drama, rating: 10)
]
當我嘗試運行它時,代碼在這里停止
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let row = indexPath.row
// When I try to open the view with the TableView the code breaks in this line
cell.textLabel?.text = movies[row].title
return cell
}
總的來說,我對Swift和iOS開發還很陌生,所以我不確定哪里出錯了。 讓我知道是否需要發布更多代碼。 謝謝!
為了創建一個單元格,使用方法:
cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)) as UITableViewCell
該方法為給定的行創建一個新的單元格,或重用現有的單元格(以使滾動更流暢)
“單元格標識符”是您在情節提要中為自定義單元格提供的標識
確保實現UITableView
委托方法以創建正確的行數,這樣就不會溢出電影數組,這也可能導致崩潰
有一個例子在這里在迅速簡單的表視圖implemenetation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.