繁体   English   中英

iOS Swift制作表格列表不断出现错误

[英]ios swift making table list keep getting error about nill

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! CustomTableViewCell

     let text = data[indexPath.row]

     cell.label.text = text

     return cell
}

上面是我看到要遵循的代码。

我的代码如下

在此处输入图片说明

我不知道为什么它在tableView.dequeueReusableCell(withIdentifier:“ locCell”)上获得零值

我的故事板如下

在此处输入图片说明

我添加了如下标识符(您可以在图片的右下部分看到它

在此处输入图片说明

您需要注册单元以供重用。

tableView.register(LocationTableCell.self, forCellReuseIdentifier: "locCell")

或通过选择单元格,然后在右侧的属性中输入重用标识符,在情节提要中输入重用标识符。

仅仅是因为tableView.dequeueReusableCell(withIdentifier: "cell")默认为nil

尝试将其打印出来时,对于任何可选选项都是相同的情况,例如:

let optionalString: String? = ""
print(optionalString)

导致获得:

在此处输入图片说明

因此,通过将常量声明为:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

由于dequeueReusableCell(withIdentifier:)返回一个可选的UITableViewCell实例,因此cell的类型为UITableViewCell? (可选的UITableViewCell ),这就是为什么您看到此错误的原因。

如何摆脱它?

假设您已经为单元设置了单元权限标识符:

在此处输入图片说明

好吧,如果您有自定义单元格,可以将其强制转换为:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MyCustomCell else {
        // something goes wrong
        return UITableViewCell()
    }

    print(cell) // it would be fine for now

    // ...

    return cell
}

而且,如果您没有自定义单元格,那么您所要做的就是删除as? MyCustomCell as? MyCustomCell向下投放。

更换

 let cell = tableView.dequeueReusableCell(withIdentifier: "locCell")

使用此代码:

 let cell = tableView.dequeueReusableCell(withIdentifier: "locCell", for: indexPath)
  func  tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier", for: indexPath) as! CustomTableViewCell
        cell.label.text = data[indexPath.row].name
        return cell
    }

注意:在情节提要中设置tableView Delegate,DataSource并设置单元格ID cellReuseIdentifier。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM