我正在尝试使用 swift 创建 UITableViewCell 类型变量,这些是我的代码:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dwarves.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)! as UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
}
cell.textLabel?.text = dwarves[indexPath.row]
return cell
}
在第 7 行 if (cell == nil),它给我一个错误,即 Value of type 'UITableViewCell' can never be nil, comparation isn't allowed . 不能用 if ( !cell ) 代替。我应该如何修复代码?
最佳答案
如果你真的想使用过时的方法 tableView.dequeueReusableCellWithIdentifier(_:)
你可以这样做:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
cell.textLabel?.text = dwarves[indexPath.row]
return cell
}
但是你最好使用dequeueReusableCellWithIdentifier(_:forIndexPath:)
它永远不会返回 nil
。
它与 registerClass(_:forCellReuseIdentifier:)
一起使用和 registerNib(_:forCellReuseIdentifier:)
.
关于ios - 在 Swift 2.0 中定义 'UITableViewCell' 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203044/