ios - 对 dequeueReusableCellWithIdentifier 使用不同的初始化方法

标签 ios swift uitableview

我想用自己的UITableViewCell类,所以在对应的UITableViewController里写

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentitfier, forIndexPath: indexPath) as MyTableViewCell //cellIdentifier is initialized
    return cell
}

但是,我想初始化我的 Cell,因为我必须在创建 Cell 时传递参数。 Apple 文档说,dequeueReusableCellWithIdentifier 调用(如果必须初始化单元格)initWithStyle:reuseIdentifier

如果有要重用的单元格,则该方法调用prepareForReuse

无论哪种方式,我都想在执行其他方法之前将参数传递到我的单元格(即分别在初始化和 prepareForReuse 中)。

执行此操作的合适方法是什么?有没有办法使用派生自 UITableViewCell (MyTableViewCell) 的类中定义的其他初始化程序?

最佳答案

如果你想有一个自定义init方法,你 (a) 需要确保你没有定义单元格原型(prototype)(因为如果你定义了,它会调用初始化程序本身);和 (b) 你的 cellForRowAtIndexPath当未找到重复使用的单元格时进行适当处理,因此您必须实例化您自己的单元格(使用您想要的任何参数。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as MyTableViewCell?

    if cell == nil {
        cell = MyTableViewCell(param1: "foo", param2: "bar", reuseIdentifier: cellIdentifier)

        // configure new cell here
    } else {
        // reconfigure reused cell here
    }

    return cell!
}

不过,就我个人而言,我不会倾向于走那条路。我宁愿利用单元原型(prototype)和标准初始化例程,但随后只根据需要重写属性(或调用一些配置函数),例如:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as MyTableViewCell

    cell.property1 = "Foo"
    cell.property2 = "Bar"

    return cell
}

这样我就可以享受单元格原型(prototype)、我的单元格对象类的自动实例化、IBOutlets 和 IBActions 的映射等,但可以在 cellForRowAtIndexPath 中执行我需要的任何特殊配置。 .

关于ios - 对 dequeueReusableCellWithIdentifier 使用不同的初始化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510477/

相关文章:

iOS 自定义 Segue 不工作

objective-c - iOS 将 short 转换为长度为 2 的字节

iOS:读取 XLS

ios - scrollview 具有不明确的可滚动内容高度和宽度

ios - didSelectRowAtIndexPath 中的 uitableViewCellaccessorytype 问题

swift - 难以检索解析对象字段值

iphone - UITableView 检测选定的单元格?

ios - Objective-C - 有没有办法将 UIView 属性作为数组?

ios - 将图像写入目录中的文件

ios - ios应用程序具有不同背景图像的自定义tableview单元格