John John - 28 days ago 12
iOS Question

TableView how to filter certain cells from the table

In a

UITableViewController
class that is responsible to populate a
TableView
with cells, I want to filter some of the cells but I can't figure out how I would do that.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}

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

let meal = meals[indexPath.row]
cell.title.text = meal.name

return cell
}


I have the attribute
meal.veg : Bool
and ideally, I want to populate the
TableView
only with meals that are
meal.veg == true
. What I am stuck with, is that I can't really understand how the
override func tableView()
does populate the table. I mean how is this function called? And how can I filter the cells.

Because the return type of the function is
UITableViewCell
and is not Optional, I have to return a cell, which doesn't allow the chance for cell filtering.

Answer

Problem - With UITableView, the method which is fired first is numberOfRowsInSection this will tell the TableView how many cell are there in the TableView, after getting the numbers the method cellForRowAtIndexPath will get fired which will used to design your TableView.

Now you are returning a count lets say 10 in numberOfRowsInSection out of which you just want to show 5 cell lets say those 5 are meal.veg == true, based on your filter meal.veg which is not possible as you need to return a cell from cellForRowAtIndexPath.

Solution - To resolve it, before reloading your table view you need to filter your array and filter out those results which are having a value meal.veg == true, then you need to pass the count of your filtered array in numberOfRowsInSection and as per that filtered array you can design your cell from cellForRowAtIndexPath