I have a tableview which is filled with fruit, vegetable ,Meat. I am having problem at this point when I change category using UIPickerView my previous data which is saved in array gets deleted.
I don't know how to handle this problem. How will I save my previous category data and also when user change category?
Below is some of my code which I am working on.
CellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "adddiseasefoodcell", for: indexPath) as! AddDiseaseTableViewCell
print(indexPath.row)
cell.foodname.text = foodname[indexPath.row]
cell.foodimg.image = imagereturn(urrl: foodimage[indexPath.row])
cell.unitlbl.text = foodunit[indexPath.row]
cell.callbl.text = foodcal[indexPath.row]
cell.switchFood.tag = indexPath.row
cell.switchFood.isUserInteractionEnabled = false
print(check[indexPath.row]!)
// check[indexPath.row] = false
if check[indexPath.row]!
{
cell.switchFood.isOn = true
}
else
{
cell.switchFood.isOn = false
}
cell.switchFood.addTarget(self, action: #selector(buttonClicked(Sender:)), for: UIControlEvents.touchUpInside)
return cell
}
SaveButtonCode
func buttonClicked(Sender:UIButton)
{
print(Sender.tag)
let index = NSIndexPath(row: Sender.tag,section:0)
let cell = foodnametableview.cellForRow(at:index as IndexPath) as! AddDiseaseTableViewCell
if check[Sender.tag]!
{
// cell.switchFood.isUserInteractionEnabled = true
cell.switchFood.isOn = false
check[Sender.tag] = false
}
else
{
// cell.switchFood.isUserInteractionEnabled = true
cell.switchFood.isOn = true
check[Sender.tag] = true
}
}
You need to create different Arrays for each of your Category. And than you have to do it like that:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if selectedCategory == .meat {
return meatArray.count
}
// same for other Catgories
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Create cell and other configurations
if selectedCategory == .meat {
let selectedFood = meatArray(indexPath.row)
//use selectedFood object to get values and use it in the cell
}
return cell!
}