我正在尝试使用 Swift 在 TableView 中显示电影列表。基本上,一个 Movie 对象有标题、评级、流派等。
这是 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 代码中,我用它来保存电影对象列表
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
该方法为给定行创建一个新单元格或重用现有单元格(为了使滚动更平滑)
“CellIdentifier” 是您在 Storyboard中为自定义单元格提供的标识
确保您实现了 UITableView
委托(delegate)方法来创建正确的行数,这样您就不会溢出您的电影数组,这也可能导致您的情况崩溃
有一个例子here在 swift 中实现简单的 TableView
关于ios - Swift - 使用自定义类作为 TableView 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004917/