【发布时间】:2011-07-26 20:46:35
【问题描述】:
是否有一种简单的方法可以在点击单元格时实现复制菜单,而不是继承 UITableViewCell?
谢谢,
强化学习
【问题讨论】:
标签: uitableview uimenucontroller
是否有一种简单的方法可以在点击单元格时实现复制菜单,而不是继承 UITableViewCell?
谢谢,
强化学习
【问题讨论】:
标签: uitableview uimenucontroller
在 iOS 5 中,一个简单的方法是实现 UITableViewDelegate 方法:
- (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
通过实现 3 个委托,它可以在长按手势后为您调用 UIMenuController。例如:
/**
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];
}
}
【讨论】:
是的!
在- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath(UITableView 的委托方法)中调用[[UIMenuController sharedMenuController] setMenuVisible:YES animated:ani](其中ani 是一个BOOL,用于确定控制器是否应该被动画化)
编辑:UIMenuController 上的“复制”命令默认不会复制 detailTextLabel.text 文本。但是,有一种解决方法。将以下代码添加到您的类中。
-(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];
}
}
【讨论】:
tableView:didSelectRowAtIndexPath里面,那么当你以普通方式选择行时UIMenuController就会出现(我猜这就是你想要的)