iOS实现UITableView选中效果[OC版+Swift版]

421 阅读1分钟

前言

在开发项目中我们经常会遇到给UITableView设置单选和多选效果的需求,整理如下OC和Swift的代码

OC版本

1.将UITableView开启编辑模式

//设置编辑模式,并设置动画
[self.mainTabView setEditing:YES animated:YES];

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;

}

2.更新TableViewCell选择状态

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView.isEditing) {

        return;

    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

3.替换TableViewCell为自定义图标


{

    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;

                    img.highlighted = YES;

                    if (self.selected) {

                        img.highlightedImage = [UIImage imageNamed:@"caidun_recording_luyin_danxuanSelect"];

                        img.image=[UIImage imageNamed:@"caidun_recording_luyin_danxuanSelect"];

                    }else

                    {

                        img.highlightedImage = [UIImage imageNamed:@"caidun_recording_luyin_danxuan"];

                        img.image = [UIImage imageNamed:@"caidun_recording_luyin_danxuan"];

                    }

                }

            }

        }

    }

    [super layoutSubviews];

}

Swift版本

1.创建记录选中索引的数组

fileprivate var deletedIndexPaths = [IndexPath]()

2.将UITableView开启编辑模式

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

3.将UITableViewCell 索引加入数组

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if(tableView.isEditing) {

            deletedIndexPaths.append(indexPath)

        } else {

            ///跳转code

        }

    }

4.将UITableViewCell 索引移除数组

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        if(tableView.isEditing) {

            deletedIndexPaths.removeAll { (index) in

                return index.row == indexPath.row

            }
        }
    }