您的位置:首页 > 移动开发 > IOS开发

iOS tableView多选,长按弹出菜单

2016-05-18 16:20 351 查看
1、tableView支持多选cell和单选cell,默认是单选的,如果要开启多选,需要定义tableView的一个属性,

//    self.tableView.allowsMultipleSelection = YES; // 支持多选
//    self.tableView.allowsMultipleSelectionDuringEditing = YES; // 编辑状态下支持多选


2、其实tableView默认是支持cell的长按动作的,长按弹出菜单包括粘贴,复制,删除等等,但是必须实现tableView的3个方法,

//  允许cell长按菜单
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(5_0){
return YES;
}
// 允许可操作的Action (剪切,复制,粘贴,删除等等)
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender NS_AVAILABLE_IOS(5_0);
{
NSLog(@"%@",NSStringFromSelector(action));
return (action == @selector(copy:)); // 只支持copy
return YES; // 支持所有
}

// 操作Action
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender NS_AVAILABLE_IOS(5_0){

NSLog(@"%@",NSStringFromSelector(action));

if (action==@selector(copy:)) {//如果操作为复制
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];//黏贴板
[pasteBoard setString:cell.textLabel.text];
NSLog(@"%@",pasteBoard.string);//获得剪贴板的内容
}

}


不实现这3个方法的话,默认是不支持长按动作的。

3、很多产品的UITableViewcell支持左滑动,并且支持多种操作,扣扣的就支持置顶,删除等,

// 要想编辑cell,必须支持此方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"wfewfew");//获得剪贴板的内容
}
}
// 增加其他的操作,不返回nil的话,就会把系统的替换掉,UITableViewRowAction是iOS8之后才支持的
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {

// 执行相应的操作

}];
action1.backgroundColor = [UIColor grayColor];

UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {

// 执行相应的操作

}];

action2.backgroundColor = [UIColor blueColor];

return @[action1,action2];
}


点击相应的操作,直接在block里就可以完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: