ios - Swift - 使用自定义类作为 TableView 中的单元格

标签 ios swift

我正在尝试使用 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/

相关文章:

ios - UIImagePickerController 和 fatal error : array element cannot be bridged to Objective-C

ios - 在哪里以及如何注册接收通知的对象?

ios - 将图像从 ViewController 传递到 ViewController

ios - 添加到 Storyboard的 UIBarButtonItem 在运行时不会出现

ios - 在同一文件中的 View Controller 之间以 Swift 传递数据

ios - 将我的应用程序转换为新的 Swift - 错误 "Extra argument in call"

objective-c - 更改 UISegmentedControl selectedSegmentIndex 不会更改所选索引

iphone - CLLocationManager 仅在安装后第一次运行应用程序时监控区域

ios - swift教程新手问题

swift - 表单中各部分之间的间距