Friday, June 7, 2013

UITableView deselectRowAtIndexPath example in Objective C (iOS).

UITableView deselectRowAtIndexPath

Deselects a given row identified by index path, with an option to animate the deselection.

- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated

An index path identifying a row in the receiver.
YES if you want to animate the deselection and NO if the change should be immediate.

Discussion of [UITableView deselectRowAtIndexPath]
Calling this method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.

Calling this method does not cause any scrolling to the deselected row.

UITableView deselectRowAtIndexPath example.
In your didSelectRowAtIndexPath you need to call deselectRowAtIndexPath to deselect the cell.

So whatever else you are doing in didSelectRowAtIndexPath you just have it call deselectRowAtIndexPath as well.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Do some stuff when the row is selected
 [tableView deselectRowAtIndexPath:indexPath animated:YES];

Example of [UITableView deselectRowAtIndexPath].
- (void)viewDidDisappear:(BOOL)animated
    NSIndexPath *selected = [self.tableView indexPathForSelectedRow];
    if ( selected ) [self.tableView deselectRowAtIndexPath:selected animated:NO];

    [self.tableView beginUpdates];
    [self.tableView endUpdates];

UITableView deselectRowAtIndexPath example.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {

        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        selectedRowIndex = nil;


    else {  self.selectedRowIndex = [indexPath retain];   }

    [tableView beginUpdates];
    [tableView endUpdates];


End of UITableView deselectRowAtIndexPath example article.