UITableViewCell自定义左滑删除按钮

  1. 建立一个可变数组, 可以删除的, 作为测试数据
    @property (nonatomic, strong) NSMutableArray *arrM;

初始化:
_arrM = [[NSMutableArray alloc] initWithObjects:@”1”,@”2”,@”3”,@”4”,@”5”,@”6”,@”7”,@”8”,@”9”,@”10”,@”11”,@”12”, nil];

2.实现关键代理方法
这里仅做两个自定义按钮

  • (NSArray )tableView:(UITableView )tableView editActionsForRowAtIndexPath:(NSIndexPath )indexPath
    {
    //UITableViewRowAction是iOS8才有的,title不想要打了空格占着大小
    UITableViewRowAction
    deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@” “ handler:^(UITableViewRowAction action, NSIndexPath indexPath) {

[self.arrM removeObjectAtIndex:indexPath.row];
[tableView reloadData];

NSLog(@”点击删除”);
}];

UITableViewRowAction shareRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@” “ handler:^(UITableViewRowAction action, NSIndexPath *indexPath) {
NSLog(@”点击分享”);
}];

// 这个地方:先加入的在右边
return @[shareRowAction, deleteRowAction];
}

3.在自定义cell的.m文件中重写layoutSubviews方法

-(void)layoutSubviews {

for (UIView *subView in self.subviews) {
if([subView isKindOfClass:NSClassFromString(@”UITableViewCellDeleteConfirmationView”)]) {

// 拿到subView之后再获取子控件

// 因为上面删除按钮是第二个加的所以下标是1
UIView deleteConfirmationView = subView.subviews[1];
//改背景颜色
deleteConfirmationView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:42.0/255.0 blue:62.0/255.0 alpha:1.0];
for (UIView
deleteView in deleteConfirmationView.subviews) {

self.deleteImage.contentMode = UIViewContentModeScaleAspectFit;
self.deleteImage.image = [UIImage imageNamed:@”ceshi1”];
self.deleteImage.frame = CGRectMake(0, 0, deleteView.frame.size.width, deleteView.frame.size.height);
[deleteView addSubview:self.deleteImage];
}

// 这里是右边的
UIView shareConfirmationView = subView.subviews[0];
shareConfirmationView.backgroundColor = [UIColor colorWithRed:142.0/255.0 green:201.0/255.0 blue:75.0/255.0 alpha:1.0];
for (UIView
shareView in shareConfirmationView.subviews) {

self.shareImage.contentMode = UIViewContentModeScaleAspectFit;
self.shareImage.image = [UIImage imageNamed:@”ceshi2”];
self.shareImage.frame = CGRectMake(0, 0, shareView.frame.size.width, shareView.frame.size.height);
[shareView addSubview:self.shareImage];
}
}
}

}

注意一: 其中我们在添加图片时应该注意使用懒加载的控件方式去定义, 不然会导致多次调 layoutSubviews 方法, 多次添加image
注意二: 我们在设置cell的时候要注意做判空处理