1. 程式人生 > >iOS 使用自定義按鈕刪除對應cell

iOS 使用自定義按鈕刪除對應cell

很多app設計的時候因為各種原因,導致tableView不能通過右滑cell的選單來刪除相應的cell。這種情況下刪除按鈕通常放在對應的自定義cell上,如下圖:

之前我的刪除功能都是通過 刪除資料來源對應元素,然後通過tableView reloadData 來實現刪除功能。這樣做有兩個小問題:

1.每刪除一個都需要reloadData,感覺很浪費

2.沒有刪除的動畫效果,體驗不好

於是按照自己的想法改動了一番,效果如下:


以下是實現方法:

自定義的cell通過block將自己傳給控制器(這裡必須要獲得cell的引用,因為刪除第一次後

cellForRowAtIndexPath代理方法中的indexPath可能會錯誤,需要通過cell獲取準確的indexPath

在block中執行deleteRowsAtIndexPaths方法,其中傳入的是當前cell的indexPath

beginUpdates和endUpdates最好加上,可以讓動畫效果更佳同步和順滑(蘋果說的)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

MyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell"];

    cell.str

= [self.dataArr objectAtIndex:indexPath.row];

    cell.deleteBlock = ^(UITableViewCell *currentCell){

//獲取準確的indexPath

        NSIndexPath *currentIndexPath = [_tableView indexPathForCell:currentCell];

//        NSString *value = _dataArr[currentIndexPath.row];

        [self.dataArr removeObjectAtIndex:currentIndexPath.row

];

//beginUpdates和endUpdates中執行insert,delete,select,reload row時,動畫效果更加同步和順滑,否則動畫卡頓且table的屬性(如row count)可能會失效

        [self.tableView beginUpdates];

//這裡不能直接使用cellForRowAtIndexPath代理方法中傳入的indexPath,因為在刪除一次後如果繼續向下刪除,indexPath會因為沒有重新整理而產生錯誤

        [self.tableViewdeleteRowsAtIndexPaths:@[currentIndexPath]withRowAnimation:UITableViewRowAnimationFade];

        [self.tableView endUpdates];

    };

    return cell;

}