Reputation: 1903
Well i know these types of questions are answered by SO before, but mine is little different so please read it.
I am using a button inside tableview cell. On click of button i am showing an AlertViewController with list of actions. On selecting action my button text and my custom model class propery is changed.
Button text is changing on button click. But my problem is cell not storing button state. If i change button of 1st cell and then click on second cell button all other buttons back to its default text.
Here is my code
setting cell data
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("dbColumns", forIndexPath: indexPath) as! CustomColumnTableViewCell
let column = columns[indexPath.row]
cell.dbColumnName.text = column.name
cell.dbColumnOrder.titleLabel?.text = column.order
cell.dbColumnOrder.tag = indexPath.row
print(columns)
cell.dbColumnOrder.addTarget(self, action: #selector(ViewController.showAlert(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
Action on button click
//MARK:Show Alert
func showAlert(sender:UIButton){
let alert = UIAlertController(title: "Column Order", message: "Please select column order", preferredStyle: .ActionSheet)
let index = sender.tag
let indexPath = NSIndexPath(forRow: index, inSection: 0)
alert.addAction(UIAlertAction(title: "None", style: .Default, handler: { (action) in
//execute some code when this option is selected
self.columns[index].order = "None"
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}))
alert.addAction(UIAlertAction(title: "Assending", style: .Default, handler: { (action) in
//execute some code when this option is selected
self.columns[index].order = "Assending"
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}))
alert.addAction(UIAlertAction(title: "Desending", style: .Default, handler: { (action) in
//execute some code when this option is selected
self.columns[index].order = "Desending"
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
Please hemp me.
Upvotes: 2
Views: 2183
Reputation: 3310
In cellForRowAtIndexPath
method Set button text like this way
First remove this
cell.dbColumnOrder.titleLabel?.text = column.order
Replace this
cell.dbColumnOrder.setTitle("\(column.order)", for: .normal)
And one more thing you need to increase cell.dbColumnOrder
width.
Hope it works
Upvotes: 8