自定义 TableViewCell 错误:无条件快速动态_cast 类

问题描述 投票:0回答:3

我收到错误,因为以下内容的 swiftdynamic_cast 类无条件,

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      var   cell :CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as CustomTableViewCell;    // error here

        return cell
    }

请帮我解决这个问题。 谢谢!

ios uitableview swift dynamic-cast
3个回答
0
投票

dequeueReusableCellWithIdentifier()
返回类型为
AnyObject
的可选值。因此,力型铸造可能会引起问题。如果你使用
as?
进行类型转换,我想

  var   cell :CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as? CustomTableViewCell; 

   // cell will not be nil if you registered already. Bt this if check may be needed to supress the warning of optional use
    if let _cell = cell{

    } 

0
投票

我找到了答案。下面的命令要添加到 viewDidLoad 方法中,您应该注册您的自定义单元格类

 self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "cell")

0
投票

在最新的 Xcode 15 或更高版本中,我们不需要在 tableview 中添加注册自定义单元格类。如果您尝试添加 tableview 自定义单元格类,您将收到 unwrap 可选错误

self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell")

© www.soinside.com 2019 - 2024. All rights reserved.