How to use multiple UITableView in single view Controller in iOS – Swift – Code Utility

I am new to iOS development. Currently, I am working on a project in which I use more than two UITableViews in a single view controller, but both data sources come from server one by one. When the first api hit, it shows the result, but after select item from that list I am unable to show the response in list.

Here is my code:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("sdfsdfsf")
    var count:Int?
    if tableView == self.pat_search_listview {
        count = serach_data.count
    }
    else  if tableView == self.visit_listview {
        count = all_vist_data.count
    }
    return count!
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    if tableView == self.pat_search_listview {
        cell.textLabel?.text = serach_dataindexPath.row.name + "     " + serach_dataindexPath.row.id
    }
        
        
    else  if tableView == self.visit_listview {
        print("second listview")
        cell.textLabel?.text = all_vist_dataindexPath.row.date
    }
    
    return cell
}

,

check the Outlet connections for both tableViews… both shouldn’t be nil in viewDidLoad

in viewDidLoad:

self.pat_search_listview.dataSource = self; 
self.visit_listview = self;

self.pat_search_listview.tag = 0
self.visit_listview.tag = 1

in

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

if tableView.tag == 0
...
else
...

,

Make sure to set delegate and data source and don’t forget to reload the table after adding/updating the arrays.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    if tableView == self.pat_search_listview
    {
        return serach_data.count/*pat_search_listview's Array count*/
    }
    else  if tableView == self.visit_listview
    {
        return all_vist_data.count/*visit_listview Array count*/
    }
}

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

    if tableView == self.pat_search_listview
    {
        cell.textLabel?.text = serach_dataindexPath.row.name + "     " + serach_dataindexPath.row.id
    }
    else  if tableView == self.visit_listview
    {
        print("second listview")
        cell.textLabel?.text = all_vist_dataindexPath.row.date
    }

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if tableView == self.pat_search_listview
    {
        //--- Item at index from pat_search_listview
    }
    else  if tableView == self.visit_listview
    {
        print("second listview")
        //--- Item at index from visit_listview
    }
}

Leave a Comment