Martheli Martheli - 9 months ago 29
iOS Question

How to only load table view after search?

I am looking to create a view controller that has a way for a user to search for devices and then after they click the search button, I want the table view below to be populated. The problem is the tableview is loading right as the view controller is loaded and since the user has not searched for anything yet, the app crashes since theres no data being populated in the table. I want the tableview to not load until the user clicks the search button.

So far I have the following:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell

cell.deviceName.text = deviceArray[indexPath.row]

return cell
}


How do I get this to not load until user clicks the search button first?

Answer Source

In the interface builder don't link your tableView.dataSource as self, and then in the action of your search button use this code after your search logic

 self.tableView.dataSource = self
 self.tableView.reloadData()

I hope this helps you, best regards