在 tableView 中有時候會對其進(jìn)行增刪操作.這里就來看看怎么增刪.主要是使用系統(tǒng)的,而不是自定義的.
對于系統(tǒng)的可編輯狀態(tài)我們可以看到有三種:
UITableViewCellEditingStyleNone,
UITableViewCellEditingStyleDelete,
UITableViewCellEditingStyleInsert
這三種對應(yīng)的是那哪種狀態(tài)呢?
UITableViewCellEditingStyleNone
UITableViewCellEditingStyleDelete
UITableViewCellEditingStyleInsert
這三種是系統(tǒng)給的三種樣式,那么有時候我們需要進(jìn)行多行操作;比如下面的圖所示:
沒有這個啊....這時候很多人會想到自定義了.其實這個系統(tǒng)也是給寫好的.而且對于 cell 的循環(huán)利用問題已經(jīng)做過處理了.
下面看一下重點,實現(xiàn)這個多選有兩種方法:
1>使用 tableView 的屬性:
@property (nonatomic) BOOL allowsMultipleSelectionDuringEditing
allowsMultipleSelectionDuringEditing這個屬性默認(rèn)是 NO, 設(shè)置成 YES. 就是出現(xiàn)多選.
2>使用 tableView 的代理方法.我們知道上面代理只有三個選項,沒有多選的枚舉值.
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
// 當(dāng)我們 使用兩個枚舉值的按位或時,就會發(fā)現(xiàn)多選出現(xiàn)了.
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
當(dāng)然如果需要這種效果,不要忘記設(shè)置為可編輯[self setEditing:YES animated:YES];
注意:
如果需要自定義多選效果的話,一定要在數(shù)據(jù)模型中定義是否選中狀態(tài).否則 cell 循環(huán)利用,會使得選中的行有問題.刪數(shù)據(jù)時要注意的是刪除相應(yīng)數(shù)據(jù)后,重新刷新一下表格.刪除的數(shù)據(jù),和刪除的表格一定要對應(yīng)起來.
附錄:
1> 左滑出現(xiàn)刪除按鈕
// 1.確保cell 可以被編輯
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
// 2.左滑后點擊 delete 之后,會調(diào)用下面的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%@", indexPath);
}
// 注意:這個方法可以不去寫,如果寫了必須 return 的是UITableViewCellEditingStyleDelete,否則不會出現(xiàn)側(cè)滑效果
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
3.如果希望修改標(biāo)題的話.
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
// 測試用
return @"haha";
}
改變側(cè)滑右側(cè)文字
由于現(xiàn)在越來越多的新需求產(chǎn)生,很多時候我們側(cè)滑會出多個選項.從 iOS 以后,蘋果也有了相應(yīng)的方法:
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
// 使用 Block 回調(diào),實現(xiàn)點擊后的方法
UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"增加" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"%@", indexPath);
}];
UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"減少" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"%@", indexPath);
}];
// 蘋果的習(xí)慣,右側(cè)的多個按鈕,顯示位置是反著的
return @[action, action1];
}