修改UITableViewCell编辑状态下的图片

由于项目需求,cell编辑状态下左边的删除图片和右边的移动的图片不能使用系统的,可以使用下面方法修改图片

1.在自定义cell的初始化方法中自定义删除按钮

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.deleteButton setImage:[UIImage imageNamed:@"qudiao"] forState:UIControlStateDisabled];
        self.deleteButton.frame = CGRectMake(10, 15, 15, 15);
        self.deleteButton.hidden = YES;
        //由于不知道如何主动让cell显示右边的删除按钮,所以这里并没有给按钮添加点击事件,而是把按钮设置为不可点击状态,实际上点击响应的还是系统自带的删除按钮
        self.deleteButton.enabled = NO;
        self.deleteButton.backgroundColor = [UIColor whiteColor];
        //这个一定要加在cell上,不能添加到contentView上,否则进入编辑模式后会跟随contentView右移
        [self addSubview:self.deleteButton];
    }
    return self;
}

 

2.重写setEditing方法

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:NO];
    //控制是否显示删除按钮
    self.deleteButton.hidden = !editing;
    
    //修改右边的移动按钮的图片
    if (editing) {
        for (UIView * view in self.subviews) {
            if ([NSStringFromClass([view class]) rangeOfString: @"Reorder"].location != NSNotFound) {
                for (UIView * subview in view.subviews) {
                    if ([subview isKindOfClass: [UIImageView class]]) {
                        ((UIImageView *)subview).image = [UIImage imageNamed: @"yidong"];
                    }
                }
            }
        }
    }
    
    //隐藏修改编辑模式下删除按钮图片
    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.frame = CGRectZero;
                    //网上有的方法让在这边修改图片,而不是再创建一个按钮,自己尝试了下发现有图片变形,或者移动cell时仍然会显示系统图片等问题,所以我没有采用这种方法,而是在这里设置为nil
                    img.image = nil;
                }
            }
        }
    }
}

 

posted @ 2017-09-06 17:04  YouNeedCourage  阅读(1001)  评论(0编辑  收藏  举报