iOS 自定义UITabView左滑样式及滑动背景UISwipeActionPullView

1.自定义左滑样式

单个左滑按钮的情况下可以使用图片转color的方式设置UITableViewRowAction的背景色:

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //删除动作
    }];

    deleteAction.backgroundColor = [UIColor colorWithPatternImage:[self setBackImageView]];
    
    return @[deleteAction];
}

//自定义视图
-(UIImage *)setBackImageView{
    UIButton *btn = [UIButton buttonWithType:0];
    btn.frame = CGRectMake(0, 0, 100, 124);
    btn.backgroundColor = kMainColor;
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(30, 46, 16, 18)];
    imageV.image = kIMAGE_Name(@"shop_car_deleteIcon1");
    [btn addSubview:imageV];
    
    UILabel *titleLabel = [btn createLabelFrame:CGRectMake(20, 70, 36, 20) textColor:kWhiteColor font:kFont(13)];
    titleLabel.text = @"删除";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    return [UIView convertViewToImage:btn];
}

view的扩展方法

@implementation UIView (Extention)
//View转Image
//使用该方法不会模糊,根据屏幕密度计算
+ (UIImage *)convertViewToImage:(UIView *)view {
    
    UIImage *imageRet = [[UIImage alloc]init];
    //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度);
    UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageRet;
    
}
@end

这时候可能会出现UI上的瑕疵,如图:

image.png

图上的浅灰色是由于视图UISwipeActionPullView的默认背景色,这时候就需要找到对应的视图进行更改

2.查找UISwipeActionPullView

step1.在tableview的代理方法willBeginEditingRowAtIndexPath里调用

这一步必须进行,否则当前控制器的viewWillLayoutSubviews不会执行

[self.view setNeedsLayout];
step2.重写viewWillLayoutSubviews方法,查找到UISwipeActionPullView
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    UIView *targetView;
       for (UIView *t_subView in self.shopcartTableView.subviews) {
           if (@available(iOS 13.0, *)) {
               if ([NSStringFromClass([t_subView class]) isEqualToString:@"_UITableViewCellSwipeContainerView"]) {
                   for (UIView *t2_subView in t_subView.subviews) {
                       if ([NSStringFromClass([t2_subView class]) isEqualToString:@"UISwipeActionPullView"]){
                           targetView = t2_subView;
                       }
                   }
               }
           } else {
               if ([NSStringFromClass([t_subView class]) isEqualToString:@"UISwipeActionPullView"]){
                   targetView = t_subView;
               }
           }
           targetView.backgroundColor = kBackgroundColor;
           NSLog(@"====%@",targetView);
       }
}

你可能感兴趣的:(iOS 自定义UITabView左滑样式及滑动背景UISwipeActionPullView)