首页 > 解决方案 > 在一个 ViewController Swift 中使用两个 UITableView

问题描述

如何在一个 ViewController 中创建两个 UITableView,我有一个问题

您需要每个返回的问题都不在条件范围内,我有每个 Tableview 的信息

此消息:“预期返回'Int'的函数中缺少返回”

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == table_View {
    return list.count
    }

    if tableView == table_View2 {
    return list_2.count
    }
}

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

    if tableView == table_View {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell_1") as! TableView_Cell
    cell.la_view.text = list[indexPath.row]
    cell.backgroundColor = UIColor(named: "Defeult")

    return cell
    }

    if tableView == table_View2 {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell_2") as! TableView_Cell
    cell.la_view2.text = list_2[indexPath.row]
    cell.backgroundColor = UIColor(named: "Defeult")

    return cell
    }

}

标签: swiftuitableview

解决方案


问题是,例如在任何情况下numberOfRowsInSection都必须返回一些东西。在您的实现中,您有两个if语句,而您,但只有您知道这就足够了,因为tableView只能是两者中的任何一个。不幸的是,编译器不知道这一点。因此,您可以通过一种简单的方式来做到这一点:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == table_View {
        return list.count
    }
    return list_2.count
}

注意:同样适用于cellForRowAt功能

可能更好:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == table_View {
        return list.count
    } else if tableView == table_View2 {
        return list_2.count
    } 
    assertionFailure("Unexpected tableView")
    return 0
}

推荐阅读