UITableViewCell checkmark change on select
swift:
var selectedCell:UITableViewCell?{
willSet{
selectedCell?.accessoryType = .None
newValue?.accessoryType = .Checkmark
}
}
then:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedCell = self.tableView.cellForRowAtIndexPath(indexPath)
self.mapView.selectAnnotation(self.mapView.annotations[indexPath.row], animated: true)
}
Another solution:
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSIndexPath *oldIndex = [self.tableView indexPathForSelectedRow];
[self.tableView cellForRowAtIndexPath:oldIndex].accessoryType = UITableViewCellAccessoryNone;
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
return indexPath;
}
And yeah: you don't have to check if oldIndex
is nil
:)
Swift 3 and later:
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let oldIndex = tableView.indexPathForSelectedRow {
tableView.cellForRow(at: oldIndex)?.accessoryType = .none
}
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
return indexPath
}
Keep a property in your view controller called
selectedRow
, which represents the index of a row that represents the checked item in a table section.In your view controller's
-tableView:cellForRowAtIndexPath:
delegate method, set theaccessoryType
of thecell
toUITableViewCellAccessoryCheckmark
if the cell'sindexPath.row
equals theselectedRow
value. Otherwise, set it toUITableViewCellAccessoryNone
.In your view controller's
-tableView:didSelectRowAtIndexPath:
delegate method, set theselectedRow
value to theindexPath.row
that is selected, e.g.:self.selectedRow = indexPath.row
Zyphrax suggested a great solution that worked great for me! And if you need to clear the previous selected row, just use:
[self.tableView reloadData];
in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath