Cor*_*rdt 7 uitableview ios swift
我想使用自己的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
}
Run Code Online (Sandbox Code Playgroud)
但是,我希望初始化我的Cell,因为我必须在创建时传递参数.Apple文档说,dequeueReusableCellWithIdentifier调用(如果必须初始化一个单元格)initWithStyle:reuseIdentifier.
如果有一个要重用的单元格,则该方法调用prepareForReuse.
无论哪种方式,我想在执行其他方法之前将参数传递给我的单元格(即分别在初始化和prepareForReuse中).
执行此操作的适当方法是什么,是否有一种方法可以使用从UITableViewCell(MyTableViewCell)派生的类中定义的其他初始值设定项?
如果您想要一个自定义init方法,您 (a) 需要确保您没有定义单元原型(因为如果您这样做,它将调用初始化器本身);(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!
}
Run Code Online (Sandbox Code Playgroud)
但就我个人而言,我不会倾向于走那条路。我宁愿利用单元原型和标准初始化例程,但然后根据需要重写属性(或调用一些配置函数),例如:
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
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以享受单元原型、单元对象类的自动实例化、IBOutlet 和 IBActions 的映射等,但可以在cellForRowAtIndexPath.
| 归档时间: |
|
| 查看次数: |
2209 次 |
| 最近记录: |