我似乎无法完成这项工作,单元格的文本标签显示为空:
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/