要如何實(shí)現(xiàn)tableView的多選呢下面我總結(jié)了一下,只需要實(shí)現(xiàn)四個(gè)方法就能實(shí)現(xiàn)cell的多選模式
首先tableView的必須實(shí)現(xiàn)的協(xié)議方法不包含在四個(gè)方法里面,其中一個(gè)是UIViewcontroller里的方法,并不是協(xié)議方法.但是執(zhí)行此方法會(huì)有一個(gè)bug,當(dāng)你提交兩種style時(shí)(在第二個(gè)實(shí)現(xiàn)方法中)不能實(shí)現(xiàn)滑動(dòng)刪除.
其中第一個(gè)方法是UIViewcontroller
的方法 設(shè)置可編輯模式
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[_tableView setEditing:editing animated:animated];
if (editing) {
// no done
} else {
// delete selected array
[array removeObjectsInArray:_selectedArray]; // selected component added array
[_tableView deleteRowsAtIndexPaths:_selectedIndexArray withRowAnimation:UITableViewRowAnimationLeft]; // selected indexPath added array
[_selectedIndexArray removeAllObjects]; // empty array component
[_selectedArray removeAllObjects]; // empty array component
}
}
第二個(gè)實(shí)現(xiàn)方法UITableViewdelegate
返回style
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
// selected deleteStyle and insertStyle at the same time
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
第三個(gè)實(shí)現(xiàn)方法UITableViewdelegate
方法功能是選中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.editing) {
[_selectedIndexArray addObject:indexPath]; // add indexPath to array
[_selectedArray addObject:_array[indexPath.row]];// add component to array
}
}
第四個(gè)實(shí)現(xiàn)方法是UITableViewdelegate
方法是取消
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.editing) {
[_selectedArray removeObject:_array[indexPath.row]]; // delete selected component
[_selectedIndexArray removeObject:indexPath]; // delete selected indexPath
}
}
另外怎樣實(shí)現(xiàn)單個(gè)cell的多功能呢,下面的方法能夠解決此問題
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"刪除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[_nameArr removeObjectAtIndex:indexPath.row];
[_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}];
return @[rowAction]; // can add more rowAction to complete other operation
}