Saturday, June 8, 2013

UITableView tableView willSelectRowAtIndexPath example in Objective C (iOS).

UITableView tableView willSelectRowAtIndexPath

Tells the delegate that a specified row is about to be selected.

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath

Parameters of [UITableView tableView willSelectRowAtIndexPath]
A table-view object informing the delegate about the impending selection.
An index path locating the row in tableView.

Return Value of [UITableView tableView willSelectRowAtIndexPath]
An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don'€™t want the row selected.

Discussion of [UITableView tableView willSelectRowAtIndexPath]
This method is not called until users touch a row and then lift their finger; the row isn'€™t selected until then, although it is highlighted on touch-down. You can use UITableViewCellSelectionStyleNone to disable the appearance of the cell highlight on touch-down. This method isn’t called when the table view is in editing mode (that is, the editing property of the table view is set to YES) unless the table view allows selection during editing (that is, the allowsSelectionDuringEditing property of the table view is set to YES).

UITableView tableView willSelectRowAtIndexPath example.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // rows in section 0 should not be selectable
    if ( indexPath.section == 0 ) return nil;

    // first 3 rows in any section should not be selectable
    if ( indexPath.row =< 2 ) return nil;

    // By default, allow row to be selected
    return indexPath;

Example of [UITableView tableView willSelectRowAtIndexPath].
- (NSIndexPath *)tableView:(UITableView *)tv willSelectRowAtIndexPath:(NSIndexPath *)path
    // Determine if row is selectable based on the NSIndexPath.

    if (rowIsSelectable)
        return path;

    return nil;

UITableView tableView willSelectRowAtIndexPath example.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        CommentViewController *commentViewController = [[CommentViewController alloc] initWithNibName:@"CommentViewController" bundle:nil];
        Comment *selectedComment = [[[Comment alloc] init] retain];
        selectedComment = [self.message.comments objectAtIndex:indexPath.row];
        commentViewController.comment = selectedComment;

        [self presentModalViewController:commentViewController animated:YES];

        [selectedComment release];
        [commentViewController release];   

End of UITableView tableView willSelectRowAtIndexPath example article.