UITableView如何实现左滑删除功能?

UITableView如何实现左滑删除功能?
步骤如下:

- 1.实现UITableView数据源代理中的一个方法即可。方法名称:`- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;`

- 2.示例代码如下:

```
// 1.只要实现这个方法,就会拥有左滑删除功能 2.点击"左滑出现的按钮"会调用这个方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 修改模型
    [self.modeArray removeObjectAtIndex:indexPath.row];
    // 刷新表格
    [self.shoppingCartTV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
```
---

#### 拓展

- 单纯的实现上面一个方法实现左滑删除功能,对于我们开发者来说,往往是不够的,很多时候我们需要自定义删除按钮的样式,例如:文字、背景图片等。

- **自定义删除按钮,**示例代码如下:

- **注意:**自定义删除按钮,首先需要先自定义UITabelViewCell,然后再自定义的cell类内部重写`layoutSubview:`方法

```
#pragma mark - layoutSubview
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    for (UIView *subView in self.subviews) {
        
        if ([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
            // 当遍历到存放删除按钮的控件时进来
            for (UIButton *btn in subView.subviews) {
                // btn的类型是_UITableViewCellActionButton类型,我们只需要把它当UIButton看待就好了
                if ([btn isKindOfClass:[UIButton class]]) {
                    // 当遍历到删除按钮时进来
                    if (btn) {
                        [btn setTitle:@"" forState:UIControlStateNormal];
                        [btn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
                        [btn sizeToFit];
                        btn.frame = CGRectMake(0, 0, btn.frame.size.width, subView.gfk_height);
                        btn.backgroundColor=[UIColor colorWithHexString:@"#0D588A"];
                    }
                }
            }
        }
    }
}
```

posted on 2016-11-14 20:22  雨过天晴Kel  阅读(144)  评论(0)    收藏  举报

导航