剛開始的時候院究,我還自己在自定義的cell里面加手勢,計算偏移量做左滑操作本涕,后來才發(fā)現(xiàn)业汰,好蠢啊,出力不討好菩颖。唉⊙幔現(xiàn)在分享一下我發(fā)現(xiàn)的新方法,都是tableView自帶的方法晦闰。完全不用在花時間自定義氛濒。
第一種产场。我直接上代碼啦~~
//tableView自帶的左滑刪除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
? ? //第二組可以左滑刪除
? ? if (indexPath.section == 2) {
? ? ? ? return YES;
? ? }?
? ? return NO;
}
// 定義編輯樣式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
? ? return UITableViewCellEditingStyleDelete;
}
// 進(jìn)入編輯模式,按下出現(xiàn)的編輯按鈕后,進(jìn)行刪除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
? ? if (editingStyle == UITableViewCellEditingStyleDelete) {
? ? ? ? if (indexPath.section == 2) {
? ? ? ? ? ?//這里做刪除操作
?? ? ? ?}
? ? }
}
// 修改編輯按鈕文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
? ? return @"刪除";
}
這就是第一種方法舞竿,直接copy可用京景,我這里是第二組的cell可以左滑,可以自己更改骗奖,也可以更改樣式确徙,不止刪除一種操作。點擊刪除 之后的我空在那执桌,自己可以添加代碼的鄙皇。
第二種,直接上代碼 哈哈哈
- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
? ? //刪除
? ? UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
? ? ? ? [self.titleArr removeObjectAtIndex:indexPath.row];
? ? ? ? completionHandler (YES);
? ? ? ? [self.tableView reloadData];
? ? }];
? ? deleteRowAction.image = [UIImage imageNamed:@"刪除"];
? ? deleteRowAction.backgroundColor = [UIColor redColor];
? ? UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
? ? return config;
}
這個方法是iOS11之后的方法仰挣,可以設(shè)置image和title 伴逸,還自帶動畫效果,體驗一下吧膘壶。