gpt4 book ai didi

ios - 使用相同的自定义单元格实现两个 UITableViews 以供重用

转载 作者:行者123 更新时间:2023-11-29 00:56:47 28 4
gpt4 key购买 nike

我目前有两个 UITableView 填充了应用程序的联系人。我有一个用于简单地查看和编辑/删除联系人,还有一个用于从列表中搜索/挑选联系人。但是,当我尝试对两个 UITableView 使用相同的自定义类单元格时,我得到了一个返回的 nil 值。

这是我的两个 cellForRowAtIndexPath 函数。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("SecondCell") as! ContactCell
let item = contacts[indexPath.row]
cell.meetupLabel?.text = item.fullName
return cell
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("FirstCell") as! ContactCell
let item = contacts[indexPath.row]
cell.label?.text = item.fullName
return cell
}

最佳答案

如果表格没有名为 FirstCellSecondCell 的单元格,dequeueReusableCellWithIdentifier(_:) 方法将返回 nil,而您将需要自己构建单元格。

// no don't do this.
let cell: ContactCell
if let c = tableView.dequeueReusableCell(withIdentifier: "FirstCell") as? ContactCell {
cell = c
} else {
cell = ContactCell(style: .default, reuseIdentifier: "FirstCell")
}

如果你想让 UIKit 为你构建单元格,你应该使用 iOS 6 中引入的 dequeueReusableCell(withIdentifier:for:):

// swift 3
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell",
for: indexPath) as! ContactCell

// swift 2
let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell",
forIndexPath: indexPath) as! ContactCell
...

此外,检查您是否在界面构建器中正确地为单元格提供了正确的重用标识符。

enter image description here

关于ios - 使用相同的自定义单元格实现两个 UITableViews 以供重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555414/

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