Используйте два UITableView в одном ViewController Swift - PullRequest
0 голосов
/ 22 октября 2018

Как я могу создать два UITableViews в одном ViewController, у меня есть одна проблема

Проблема, с которой вам нужно возвращать каждый элемент, не входит в условие, и у меня есть информация для каждого 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
    }

}

Ответы [ 4 ]

0 голосов
/ 22 октября 2018
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if tableView == table_View {
        return list.count
    }

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

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
    }
    return UITableViewCell()
}
0 голосов
/ 22 октября 2018

измените свой код внутри numberOfRowsInSection, поскольку для этого метода делегата требуется как минимум одно значение Int для случая.так как вы используете оба возвращаемых значения в условии if, возникает ошибка, запрашивающая возвращение значения в другом случае.Таким образом, каждый случай должен возвращать значение Int.

 if tableView == table_View {
    return list.count
    } 
  else {
    return list_2.count
    }
0 голосов
/ 22 октября 2018

Как быстрое решение (, пожалуйста, не забудьте прочитать остальную часть ответа ), вы можете сделать это так:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (tableView == table_View) ? list.count : 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
    }

    return UITableViewCell()
}

Важный совет:

Имейте в виду, что если вам нужно добавить два представления таблицы в одном контроллере представления (что должно быть , а не довольно крутая идея), вы можете отделить обработку dataSourceи делегировать для каждого табличного представления в различном классе (не тот же самый контроллер представления, который содержит табличные представления).Пример:

В вашем контроллере представления установите dataSource как:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let table_View = UITableView()
        let table_View2 = UITableView()

        table_View.dataSource = SourceHandler1()
        table_View2.dataSource = SourceHandler2()
    }
}

Поэтому внедрите:

class SourceHandler1: NSObject, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell_1") as! TableView_Cell
        cell.la_view.text = list[indexPath.row]
        cell.backgroundColor = UIColor(named: "Defeult")

        return cell
    }
}

class SourceHandler2: NSObject, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        list_2.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        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
    }
}

Это приводит к тому, что проблема не возникает " массивный"просмотр контроллера и уменьшение возможности получения спагетти-кода .

0 голосов
/ 22 октября 2018

Дело в том, что, например, 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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...