【问题标题】:Multiple XIBs in tableViewtableView 中的多个 XIB
【发布时间】:2018-08-12 21:20:48
【问题描述】:

这是我的 cellForRowAtIndexPath

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

    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell1") as! TableViewCell1
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell2") as! TableViewCell2
        return cell
    } else if indexPath.row == 2{
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell3") as! TableViewCell3
        return cell
    } else if indexPath.row == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell4") as! TableViewCell4
        return cell        }
}

但我仍然需要一个默认返回值,我不知道它应该是什么。

我已经在视图中注册了 xibs 确实加载了。现在他们只是显示不同的纯色背景

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.dataSource = self
    self.tableView.delegate = self

    self.tableView.register(UINib(nibName: "TableViewCell1", bundle: nil), forCellReuseIdentifier: "tablecell1")
    self.tableView.register(UINib(nibName: "TableViewCell2", bundle: nil), forCellReuseIdentifier: "tablecell2")
    self.tableView.register(UINib(nibName: "TableViewCell3", bundle: nil), forCellReuseIdentifier: "tablecell3")
    self.tableView.register(UINib(nibName: "TableViewCell4", bundle: nil), forCellReuseIdentifier: "tablecell4")
}

【问题讨论】:

  • return UITableViewCell() ?
  • 我做错了,tableView 是空的。它应该只显示 4 行不同颜色的单元格。
  • UITableView 将始终生成足够的单元格以覆盖整个屏幕(或至少覆盖其高度)

标签: ios swift4 xcode9


【解决方案1】:

是的,您需要在所有返回值的方法中发送默认值,这里cellForRowAtIndexpath 返回UITableviewcelll,因此您必须提供默认值。

您可以使用的一个技巧是:

if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell1") as! TableViewCell1
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell2") as! TableViewCell2
        return cell
    } else if indexPath.row == 2{
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell3") as! TableViewCell3
        return cell
    } else { // This will be your index 3
        let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell4") as! TableViewCell4
        return cell      
  }

【讨论】:

  • 这里编译器想要“else”的情况,所以如果所有的“if”条件都是假的,那么“else”肯定会被执行。在您的问题中,所有都是“如果”条件,但您没有指定如果所有“如果”都是错误的,该怎么办
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多