如何在 UITableViewCell 上使用自定义初始值设定项? [英] How can I use a custom initializer on a UITableViewCell?
问题描述
我有一个自定义的 UITableViewCell,我想在我的表格视图中使用它.这是我的单元格代码:
I have a custom UITableViewCell and I'd like to use it in my table view. Here's my code for the cell:
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
,我想用它来初始化单元格.但是,在我的视图控制器中,我需要使用 tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath)
.有什么方法可以让我使用我制作的自定义初始化程序吗?
I have a model class Reflection
that I'd like to initialize the cell with. However, in my view controller I need to use tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath)
. Is there any way for me to use a custom initializer like the one I made?
推荐答案
如果使用 dequeueReusableCell
,则无法更改调用的初始化方法.但是您可以编写自己的方法来更新 IBOutlets,然后在您成功使单元出列后调用该方法.
If you use dequeueReusableCell
you cannot change which initializer method that is called. But you can write your own method to update the IBOutlets which you then call after you successfully dequeue a cell.
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
}
这篇关于如何在 UITableViewCell 上使用自定义初始值设定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!