當咱們在使用tableview時,每每須要在cell左滑時顯示一個或是多個按鈕,但系統默認的只可顯示一個,如常見的刪除按鈕,那麼當咱們的需求要求要有多個按鈕時又該怎麼辦呢,咱們往下看。測試
如須要顯示多個按鈕,參照以下代碼(注意:當咱們使用自定義按鈕後,如上的系統默認方法將失去做用)
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
returntrue;
}
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnullNSIndexPath *)indexPath{
UITableViewRowAction *action1 = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleNormaltitle:@"加入黑名單"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//在block中實現相對應的事件
}];
UITableViewRowAction *action2 = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDestructivetitle:@"刪除"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[callRecordsArrremoveObjectAtIndex:indexPath.row];
//數據源刪除對應元素要在tableview刪除對應的cell以前
[tableView deleteRowsAtIndexPaths:[NSMutableArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[NSKeyedArchiverarchiveRootObject:callRecordsArrtoFile:CALLRECORDSCACHEPATH];
}];
action2.backgroundColor = [UIColorpurpleColor];
注意:一、當rowActionWithStyle的值爲UITableViewRowActionStyleDestructive時,系統默認背景色爲紅色;當值爲UITableViewRowActionStyleNormal時,背景色默認爲淡灰色,可經過UITableViewRowAction的對象的.backgroundColor設置;
二、當左滑按鈕執行的操做涉及數據源和頁面的更新時,要先更新數據源,在更新視圖,不然會出現無響應的狀況
UITableViewRowAction *toTop = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDestructivetitle:@"置頂"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//更新數據
[callRecordsArrexchangeObjectAtIndex:indexPath.rowwithObjectAtIndex:0];
//更新頁面
NSIndexPath *firstIndexPath = [NSIndexPathindexPathForRow:0inSection:indexPath.section];
[tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
}];
//此處UITableViewRowAction對象放入的順序決定了對應按鈕在cell中的順序
return@[toTop,action2,action1];
}
顯示圖形以下
在這要補充一點的就是,我在查相關資料時,上面自定義按鈕時,都加上了「orm
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath對象
{blog
}」這個方法,而我在實驗測試時發現沒有這個方法也一樣能實現預期功能,而且也沒有發現什麼bug,所以本次總結的方法只供參考,如果哪位大神知道這一點的,請不吝賜教!事件