ios - 如何在 UITableViewCell 上使用自定义初始化程序?

标签 ios swift uitableview

我有一个自定义的 UITableViewCell,我想在我的表格 View 中使用它。这是我的单元格代码:

class ReflectionCell: UITableViewCell {

@IBOutlet weak var header: UILabel!
@IBOutlet weak var content: UILabel!
@IBOutlet weak var author: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

init(data: Reflection) {
    self.header.text = data.title
    self.content.text = data.content
    self.author.text = data.author.name
    super.init(style: UITableViewCellStyle.default, reuseIdentifier: "reflectionCell")
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
}

我有一个模型类 Reflection,我想用它来初始化单元格。但是,在我的 View Controller 中,我需要使用 tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath)。有什么方法可以让我使用像我所做的那样的自定义初始化器吗?

最佳答案

如果您使用 dequeueReusableCell,则无法更改调用的初始化方法。但是您可以编写自己的方法来更新 IBOutlets,然后在您成功使单元格出队后调用该方法。

class ReflectionCell: UITableViewCell {

    @IBOutlet weak var header: UILabel!
    @IBOutlet weak var content: UILabel!
    @IBOutlet weak var author: UILabel!

    func update(for reflection: Reflection) {
        header.text = reflection.title
        content.text = reflection.content
        author.text = reflection.author.name
    }

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! ReflectionCell
    cell.update(for: reflections[indexPath.row])
    return cell
}

关于ios - 如何在 UITableViewCell 上使用自定义初始化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842034/

相关文章:

ios - Swift:如何将 UITableView 链接到单个 UIDetailView 页面

ios - IOS 中的 Tableview Controller 加载数组错误

ios - 如何在使用 swift 切换不同 View 的同时连续播放背景音乐?

使用 Xcode 6 Beta 的 UITableViewCell 宽度问题 - 使用 Size Classes

快速在 UITableView 中异步加载图像 - 顶部单元格没有图片

ios - xcode 6.1 启动屏幕启动图像空白

ios - 修复了顶部 UITableView 中的 UIImage

ios - 从状态代码字段下的响应头中获取状态消息

javascript - 如何在 webview 中显示或只读来自网站的表单? - swift

iOS/swift : mapView won't update coordinates