剛開(kāi)始的時(shí)候,我還自己在自定義的cell里面加手勢(shì),計(jì)算偏移量做左滑操作,后來(lái)才發(fā)現(xiàn),好蠢啊,出力不討好。唉?,F(xiàn)在分享一下我發(fā)現(xiàn)的新方法,都是tableView自帶的方法。完全不用在花時(shí)間自定義。
第一種。我直接上代碼啦~~
//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可以左滑,可以自己更改,也可以更改樣式,不止刪除一種操作。點(diǎn)擊刪除 之后的我空在那,自己可以添加代碼的。
第二種,直接上代碼 哈哈哈
- ( 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;
}
這個(gè)方法是iOS11之后的方法,可以設(shè)置image和title ,還自帶動(dòng)畫(huà)效果,體驗(yàn)一下吧。