Saturday, June 8, 2013

UITableView tableView shouldShowMenuForRowAtIndexPath example in Objective C (iOS).


UITableView tableView shouldShowMenuForRowAtIndexPath

Asks the delegate if the editing menu should be shown for a certain row.

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath

Parameters of [UITableView tableView shouldShowMenuForRowAtIndexPath]
tableView
The table-view object that is making this request.
indexPath
An index-path object locating the row in its section.

Return Value
YES if the editing menu should be shown positioned near the row and pointing to it, otherwise NO. The default value is NO.

Discussion of [UITableView tableView shouldShowMenuForRowAtIndexPath]
If the user tap-holds a certain row in the table view, this method (if implemented) is invoked first. Return NO if the editing menu shouldn’t be shown—for example, the cell corresponding to the row contains content that shouldn’t be copied or pasted over.

UITableView tableView shouldShowMenuForRowAtIndexPath example.
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    return (action == @selector(copy:));
}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if (action == @selector(copy:))
        NSLog(@"in real life, we'd now copy somehow");
}

Example of [UITableView tableView shouldShowMenuForRowAtIndexPath].
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return (action == @selector(copy:));
}

- (BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return YES;
}

UITableView tableView shouldShowMenuForRowAtIndexPath example.
Instead, you can use this delegate method:

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
To hide the standard items (cut, copy, and paste), return NO here:

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return NO;
}
Then you need to return YES from canBecomeFirstResponder like you have and, for some reason, I had to implement this method too:

- (BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return YES;
}

End of UITableView tableView shouldShowMenuForRowAtIndexPath example article.