美文网首页iOS收藏iOS开发你需要知道的
iOS - UITableView定制系统左滑删除按钮的样式

iOS - UITableView定制系统左滑删除按钮的样式

作者: 简了个书1993 | 来源:发表于2017-06-28 18:17 被阅读136次

开发的时候,经常会遇到 tableView 左滑删除按钮,UI设计的是各种各样的,系统提供的根本满足不了需求,也不想导入一些第三方的东西,然后各种属性设置,太麻烦,效果也不理想。那怎么来修改系统自带的呢?

先看一下效果


Simulator Screen Shot.png

下面进入正题:


141498637142.jpg

看到Cell上有这个视图,那就一定能找的到
我们在tableView的点击删除的代理方法 里边遍历cell的子视图

// 编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 点击删除的代理方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    for (UIView * sv in cell.subviews) {
        NSLog(@"%@", sv);
    }
}

下面看打印信息


191498639007.jpg

有一个名字叫UITableViewCellDeleteConfirmationView的类。

为什么我们要在tableView的点击删除的代理方法里边找,原因看图

181498637669.jpg
当删除按钮没有显示的情况下,cell子视图里是没有这个视图的,可以肯定是在左滑的时候系统把它加上去的,我们可重写cell的 insertSubview:atIndex: 这个方法,当添加 delete view 的时候,会进这个方法,那么可以在此方法中对它进行修改。

下面看下它的层级关系

151498637270.jpg

UITableViewCellDeleteConfirmationView > _UITableViewCellActionButton

图中可看到里边是一个 UIButton 的子类,那么你就可以随心所欲了

下面来修改它:

// 重写 insertSubview:atIndex 方法
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index {
    [super insertSubview:view atIndex:index];
    
    if ([view isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
        for (UIButton *btn in view.subviews) {

            if ([btn isKindOfClass:[UIButton class]]) {
                [btn setBackgroundColor:[UIColor orangeColor]];

                [btn setTitle:nil forState:UIControlStateNormal];

                UIImage *img = [image_name(@"del") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                [btn setImage:img forState:UIControlStateNormal];
                [btn setImage:img forState:UIControlStateHighlighted];
                
                [btn setTintColor:[UIColor whiteColor]];
            }
        }
    }
}

OK,运行看效果


Simulator Screen Shot.png

至此,系统的删除按钮定制完成了!

Demo:https://github.com/kssion/XPTableDeleteButtonCustom

相关文章

网友评论

    本文标题:iOS - UITableView定制系统左滑删除按钮的样式

    本文链接:https://www.haomeiwen.com/subject/habucxtx.html