show UIMenuController in UITableViewCell, grouped style

坚强是说给别人听的谎言 提交于 2019-12-05 23:58:17

Yes!
Call [[UIMenuController sharedMenuController] setMenuVisible:YES animated:ani] (where ani is a BOOL determining whether the controller should be animated) from within - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath ( UITableView's delegate method)

Edit: The 'copy' command on the UIMenuController will not by default copy the detailTextLabel.text text. However, there is a workaround. Add the following code into your class.

-(void)copy:(id)sender {
    [[UIPasteboard generalPasteboard] setString:detailTextLabel.text];
}


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if(action == @selector(copy:)) {
        return YES;
    }
    else {
        return [super canPerformAction:action withSender:sender];
    }
}
tony.tc.leung

In iOS 5, a simple way is to implement the UITableViewDelegate Methods:

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

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender 

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender 

By implementing the 3 delegates, it will enable call UIMenuController for you after a long press gesture. An example like:

/**
 allow UIMenuController to display menu
 */
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

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

/**
 if copy action selected, set as cell detail text
 */
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender 
{
    if (action == @selector(copy:))
    {
        UITableViewCell* cell = [tableView cellForIndexPath:indexPath];
        [[UIPasteboard generalPasteboard] setString:cell.detailTextLabel.text];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!