ios - 为什么不能将 UITableViewCell 实例用作计算属性?

标签 ios uitableview swift

我似乎无法完成这项工作,单元格的文本标签显示为空:

var cell:UITableViewCell {

    var c:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as? UITableViewCell

    if c == nil {
        c = UITableViewCell(style: .Value1, reuseIdentifier: "reuseIdentifier")
    }

    return c!
}

但是,如果我这样做,一切正常:

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

if cell == nil {
    cell = UITableViewCell(style: .Value1, reuseIdentifier: "reuseIdentifier")

}

我不明白为什么。我在这里遗漏了什么吗?

谢谢!

编辑:使用计算属性的代码

var cell:UITableViewCell {

    var c:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as? UITableViewCell

    if c == nil {
        c = UITableViewCell(style: .Value1, reuseIdentifier: "reuseIdentifier")
        c!.selectionStyle = .None
        c!.backgroundColor = Theme.Colors.viewBackgroundColor
        c!.textLabel?.textColor = Theme.Colors.fadedTextColor
        c!.textLabel?.font = UIFont(name: kFontDINCondRegular, size: 21.0)
        c!.detailTextLabel?.textColor = Theme.Colors.fadedTextColor
        c!.detailTextLabel?.font = UIFont(name: kFontDINCondRegular, size: 21.0)
    }

    return c!
}

switch indexPath.row {
case 0:
    cell.textLabel?.text = self.lastMonthDescription
    cell.detailTextLabel?.text = self.model.foldersContactedLastMonth.stringValue
case 1:
    cell.textLabel?.text = self.currentMonthDescription
    cell.detailTextLabel?.text = self.model.foldersContactedCurrentMonth.stringValue
case 2:
    cell.textLabel?.text = FSLocalizedString(Localizable.THIS_WEEK).uppercaseString
    cell.detailTextLabel?.text = self.model.foldersContactedCurrentWeek.stringValue
case 3:
    cell.textLabel?.text = FSLocalizedString(Localizable.TODAY).uppercaseString
    cell.detailTextLabel?.text = self.model.foldersContactedToday.stringValue
default: break

}

return cell

最佳答案

我不确定您的目标是什么,但是在您的实现中,您每次访问 cell 计算属性时都会从队列中取出一个新单元格。这意味着这两行:

cell.textLabel?.text = self.lastMonthDescription
cell.detailTextLabel?.text = self.model.foldersContactedLastMonth.stringValue

您正在创建两个不同的单元格。 然后您将在最终返回中返回一个全新的单元格。

计算属性就是这样,每次您尝试访问它们时都会计算它们,而不是实际存储在内存中。

您可以尝试使用惰性变量:

lazy var cell: UITableViewCell = {
    // blah
    return cell
}()

请注意,我在这里没有使用计算属性。相反,我分配给创建单元格的内联闭包的结果。通过使其变得惰性,它不会在第一次访问 cell 之前调用闭包,但随后将结果存储在内存中,因此您可以继续操作相同的单元格实例,而不是每次都创建一个新的单元格实例时间。

关于ios - 为什么不能将 UITableViewCell 实例用作计算属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27571736/

相关文章:

ios - 在同一 Controller 中检测 TableView 和 CollectionView 滚动

ios - 更新 UITableView 中的 UIImage

ios - iOS 上的 Firebase Crashlytics 设置?

ios - 方括号之间的 Restkit request.body 值

ios - 如何在 CoreMotion 框架中找到最小和最大频率间隔

ios - 将变量传递给为滑动加载的新 Nib

ios - NSDictionary allKeys顺序

ios - 当内容大小改变时展开 UITableViewCell

xcode - 在 Swift 中向 Xcode 项目添加和打开 PDF 文件

ios - 问题 : live updating labels/progress bars using Swift