wagashi
wagashi

Reputation: 894

ios abort didSelectRowAtIndexPath

I want to abort this method when a certain condition is not met, how should I do it?

I dont use tableView:willSelectRowAtIndexPath: method. I think it is possible to combine these two methods to prevent certain rows to be selected and be pushed into another ViewController?


EDIT:

Guys, thank you very much.

Now this code works perfectly :

- (NSIndexPath*)tableView:(UITableView *)tableView1 willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger totalcount = [totalarr count]; //totalarr is a global mutable array.

    NSIndexPath *rowToSelect = indexPath;

    if (totalcount == 0)
    {
        rowToSelect = nil;
    }
    return rowToSelect;

}

Upvotes: 1

Views: 821

Answers (2)

Adam Wright
Adam Wright

Reputation: 49386

tableView:willSelectRowAtIndexPath: is sent to the table view delegate when a row is about to be selected. Your delegate has the chance to change the selection, or cancel it entirely by returning an NSIndexPath object for the alternative selection, or nil to select nothing.

Hence, if you want to inhibit the selection of certain rows, use tableView:t willSelectRowAtIndexPath:p, do your check on p, and if you don't want that to be selected, just return nil. If you cancel the selection thus, tableView:didSelectRowAtIndexPath: will never be called.

Don't "cancel" things inside didXXYY type methods if you have a chance to do so in willXXYY. The did implies that the selection has been committed; UIKit might have displayed this, other event listeners might have responded, etc. It can easily lead to weird behavior.

Upvotes: 3

warrenm
warrenm

Reputation: 31782

As you mention, implement tableView:willSelectRowAtIndexPath:. Return the provided index path when you want the row to be selectable, and return nil otherwise.

Upvotes: 2

Related Questions