一、简单实现
1.设置tableView属性
self.tableView.allowsMultipleSelectionDuringEditing = YES;
2.然后在编辑按钮显示tableView编辑状态
[self.tableView setEditing:YES animated:YES];
3.查看被选中cell的indexPath数组
NSArray *indexs = self.tableView.indexPathsForSelectedRows;
二、实战使用
功能要求:
1.点击多选按钮,进入多选模式
2.满足条件的才会出现多选项(部分cell多选)
3.多选状态下,选中和取消都要获取(实时计算选中cell中某个值的总和,以及选中数量)
实现:
1.简单方法无法实现部分多选,所以用另一种方法进入编辑模式
不需要设置
self.tableView.allowsMultipleSelectionDuringEditing = YES;
实现两个代理方法
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row < 5) {
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}else{
return UITableViewCellEditingStyleNone;
}
}
ps:row<5 的显示系统自带的多选图标,否则不显示
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row < 5) {
return YES;
} else {
return NO;
}
}
ps :row<5 的会有cell向右移动,出现多选按钮的动作,否则没有动作,不会出现多选按钮
2.在选中cell的代理方法中,如果在编辑状态则处理选中事件,否则跳转其他页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// 编辑状态返回
if (tableView.isEditing) {
NSArray *indexs = tableView.indexPathsForSelectedRows;
for (NSIndexPath *index in indexs) {
// 可以取到所有选中cell的index
}
return;
}
// 正常cell点击动作
}
3、编辑状态如果取消选择的话不会进入上面方法,需要单独处理取消事件
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"取消 - %ld",indexPath.row);
}
三、其他设置
1、自带按钮颜色设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// ...
directCell.tintColor = MainTone;
// ...
}
2.判断是否在编辑状态(可用于编辑状态 是/否 切换),返回BOOL值
tableView.isEditing
3.自定义多选按钮(cell中实现)
-(void)layoutSubviews
{
for (UIControl *control in self.subviews){
if ([control isMemberOfClass:NSClassFromString(@"UITableViewCellEditControl")]){
for (UIView *v in control.subviews)
{
if ([v isKindOfClass: [UIImageView class]]) {
UIImageView *img=(UIImageView *)v;
if (self.selected) {
img.image=[UIImage imageNamed:@"xuanzhong_icon"];
}else
{
img.image=[UIImage imageNamed:@"weixuanzhong_icon"];
}
}
}
}
}
[super layoutSubviews];
}
//适配第一次图片为空的情况
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
for (UIControl *control in self.subviews){
if ([control isMemberOfClass:NSClassFromString(@"UITableViewCellEditControl")]){
for (UIView *v in control.subviews)
{
if ([v isKindOfClass: [UIImageView class]]) {
UIImageView *img=(UIImageView *)v;
if (!self.selected) {
img.image=[UIImage imageNamed:@"weixuanzhong_icon"];
}
}
}
}
}
}
4.取消选择
[tableView deselectRowAtIndexPath:indexPath animated:YES];
四、坑
千万不要设置
cell.selectionStyle = UITableViewCellSelectionStyleNone;