启用TableViewCell的滑动删除
问题
想让APP用户能从TableView中轻松删除行。
方案
在TableView的delegate中实现tableView:editingStyleForRowAtIndexPath:方法。
在dataSource中实现tableView:commitEditingStyle:forRowAtIndexPath:方法。
/* TableViewController.h */
#import <UIKit/UIKit.h>
@interface TableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *arrayOfRows;
@end
/* TableViewController.m */
- (void)viewDidLoad {
[super viewDidLoad];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
[self.view addSubview:self.myTableView];
self.arrayOfRows = [@[@"abc", @"def", @"hig"] mutableCopy];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;
if ([tableView isEqual:self.myTableView]) {
result = UITableViewCellEditingStyleDelete;
}
return result;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.myTableView setEditing:editing animated:animated];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
if (indexPath.row < [self.arrayOfRows count]) {
[self.arrayOfRows removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
}
tableView:editingStyleForRowAtIndexPath:方法能够启动删除功能,它被tableView调用,同时它的返回值决定了tableView允许用户做什么(插入,删除等)。
tableView:commitEditingStyle:forRowAtIndexPath:方法实现用户要求的删除。后一种方法在委托中定义,但是它的功能有点重载:不只使用这方法删除数据,也必须要从表中删除行。
讨论
TableView通过在目标行右侧显示一个按钮来响应滑动(图4-6)。正如你所看到的,TableView不在编辑模式下,但按钮允许用户删除行。
图4-6. 删除键出现在TableView单元格中
通过执行tableView:editingStyleForRowAtIndexPath:(在UITableViewDelegate声明)方法能够启动这个模式,它的返回值说明了表中是否应该允许同时插入与删除或者同时不。通过实现TableView的数据源中的tableView:commitEditingStyle:forRowAtIndexPath:方法,你将会得到通知(如果用户完成了插入或者删除操作的话)。
deleteRowsAtIndexPaths:withRowAnimation:方法的第二个参数允许你指定一个动画方法,当行从TableView中删除时这个动画方法会被执行。我们的示例说明了当行被删除时它在从右到左的移动过程中消失。