Xcode - cellForRowAtIndexpath - 初始化单元格

时间:2014-09-25 19:31:05

标签: xcode uitableview

这有什么区别:

var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

而且:

var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

它们对我来说似乎都很好。

PS:我知道这似乎是一个业余问题,但我是Xcode的初学者,所以没有理由沾沾自喜。

1 个答案:

答案 0 :(得分:2)

当你写:

var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

您正在使用其构造函数初始化新单元格。

当你写:

var cell = self.tableView.dequeueReusableCellWithIdentifier("cell")

您正在将单元格出列,因此您假设标识为cell的单元格已在tableView中注册。

通常,如果单元格是在Interface Builder中设计并设置为原型单元格,或者如果已使用方法self.tableView.registerClass(MyCell.classForCoder(), forCellReuseIdentifier: "cell")注册了单元格以供重用,则不需要使用构造函数,因为它已在tableView初始化。

但是如果您的单元格是以编程方式设计的,例如创建UILabelUIImage或任何组件,那么必须使用构造函数,然后使用dequeue方法

所以,如果你必须使用构造函数(因为你是按代码初始化所有东西),你的代码将如下所示:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    if cell == nil {
       cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    }

    cell.cellLabel.text = "Hello world"
    cell.cellImage.image = UIImage(named: "funny_cat.jpg")

    return cell
}

但是如果您的单元格已注册重用,或者它是原型单元格,您只需使用

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    cell.cellLabel.text = "Hello world"
    cell.cellImage.image = UIImage(named: "funny_cat.jpg")

    return cell
}


我认为查看tableview如何工作的最佳位置,您应该在这里查看官方文档:Table View Programming Guide for iOS