4.10 Displaying Context Menus on Table View Cells

本文介绍如何在UITableViewCell中实现上下文菜单功能,包括复制、粘贴等操作。通过实现三个代理方法,设置是否显示菜单及响应菜单项的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

显示上下文菜单在TableViewCell.....不懂怎么翻译
反正就是弹出复制,粘贴,选择等等的那个。

一般在手机上要复制粘贴时,我们都是先长按复制粘贴的对象。
这个过程我们要实现三个代理方法
tableView:shouldShowMenuForRowAtIndexPath:返回bool值来告诉ios这个cell是否弹出context menu
tableView:canPerformAction:forRowAtIndexPath:withSender:当时长按后,ios会多次调用这个来分别咨询是否显示“复制”、“粘贴”、“选择”......。当然了,需要上一个代理方法返回真时才有必要调用这个的。
tableView:performAction:forRowAtIndexPath:withSender:在上面的情况下,当用户点击“复制”、“粘贴”、或“选择”等,ios就会调用这个代理方法,这时你该干什么就干什么。

-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return true;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    NSLog(@"%@",NSStringFromSelector(action)); //把所有action打印出来,总共有15+个
    BOOL bPerform =(action == @selector(copy:))||(action == @selector(paste:))||(action == @selector(select:))||(action == @selector(delete:))||(action == @selector(cut:))||(action == @selector(selectAll:));

    return bPerform;//不管我怎么折腾,始终最多只有剪切、复制、选择所有、粘贴 这四个按钮
}
-(void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    UIPasteboard * pasteBoard = [UIPasteboard generalPasteboard];
    if (action == @selector(copy:)) {
        [pasteBoard setString:cell.textLabel.text];
    }else if(action == @selector(paste:)){
        cell.textLabel.text = [pasteBoard string];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值