gpt4 book ai didi

ios - 在 Swift 2.0 中定义 'UITableViewCell' 变量

转载 作者:搜寻专家 更新时间:2023-10-31 22:33:55 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com