首页 > 解决方案 > 如何将单独的 xib 单元格注册到多个表格视图?

问题描述

我有两个带有两个 xib 单元格的表格视图。如何在第二个表中注册第二个 xib 单元格?

它不断地从第一个表中放入单元格。

这是我的代码:

let cellNib = UINib(nibName: "FirstTableViewCell", bundle: nil)
self.tableView.register(cellNib, forCellReuseIdentifier: "cell")

let cellNib2 = UINib(nibName: "SecondViewCell", bundle: nil)
self.secondTableView.register(cellNib2, forCellReuseIdentifier: "cell2")

这是我的 cellForRowAt 函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


if tableView == tableView {
 let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FirstTableViewCell



    return cell
}

else  {
    let cell2 = self.secondTableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! SecondViewCell

     return cell2
}

}

标签: swiftxcodeuitableviewswift4xib

解决方案


在您的cellForRowAt函数中,有一个名为的局部变量tableView(查看函数头,tableView是第一个参数的名称),因此检查tableView == tableView总是会返回 true。这就是为什么您将始终获得第一个单元格的原因。

将该行替换为:

if tableView == self.tableView {}

通过添加self,您将直接引用类变量tableView而不是局部变量。希望这可以帮助。


推荐阅读