I am working on a project on which I have to preselect a particular cell.
I can preselect a cell using -willDisplayCell
, but I can\'t deselect it when t
If you want to select any table cell with the first click and deselect with the second, you should use this code:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.selectedIndexPath &&
[indexPath compare:self.selectedIndexPath] == NSOrderedSame) {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.selectedIndexPath = nil;
}
else {
self.selectedIndexPath = indexPath;
}
}
Swift 4:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell?.isSelected == true { // check if cell has been previously selected
tableView.deselectRow(at: indexPath, animated: true)
return nil
} else {
return indexPath
}
}
What I've found is that on top of setting the cell as selected, you have to let the table view know to select the row at the given index path.
// Swift 3+
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if appDelegate.indexPathDelegate.row == indexPath.row {
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
cell.setSelected(true, animated: true)
}
}
Swift
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// your code
// your code
// and use deselect row to end line of this function
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
Swift 3/4
In ViewController:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
In Custom Cell:
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
swift 3.0
tableView.deselectRow(at: indexPath, animated: true)