如何让iOS 10 UITableView支持长按滑动删除功能?
实现iOS 10下的长按滑动直接删除功能
嘿,这个问题我刚好踩过坑!iOS 11之后系统给UITableViewCell默认加了长按滑动直接删除的交互,但iOS 10确实没有原生支持,不过我们可以手动实现这个功能,步骤其实挺清晰的:
核心思路
iOS 10及更早版本的UITableView没有原生提供该交互,所以我们要给单元格添加长按手势识别器,模拟系统的删除逻辑,同时搭配动画让体验更贴近原生。
步骤1:给UITableViewCell添加长按手势
在你配置单元格的方法里(比如tableView:cellForRowAtIndexPath:),为每个cell添加长按手势,注意可以加个系统版本判断,避免在iOS 11+上做冗余操作:
// Swift示例 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) // 仅在iOS 10及以下添加自定义手势 if #available(iOS 11.0, *) { // 系统原生支持,无需额外操作 } else { let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:))) // 可调整长按触发时长,默认0.5秒,这里设为0.3更灵敏 longPress.minimumPressDuration = 0.3 cell.addGestureRecognizer(longPress) } // 其他cell配置逻辑... return cell }
// Objective-C示例 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YourCellID" forIndexPath:indexPath]; if (@available(iOS 11.0, *)) { // 系统原生支持,无需额外操作 } else { UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 0.3; [cell addGestureRecognizer:longPress]; } // 其他cell配置逻辑... return cell; }
步骤2:处理长按手势的删除逻辑
实现手势触发后的处理方法,核心是模拟系统的编辑模式动画,然后执行删除操作:
// Swift示例 @objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) { // 只在手势开始时触发 guard gesture.state == .began, let cell = gesture.view as? UITableViewCell else { return } guard let indexPath = tableView.indexPath(for: cell) else { return } // 先让cell进入编辑模式,模拟滑动出删除按钮的动画 tableView.setEditing(true, animated: true) // 延迟0.2秒执行删除,让动画更自然 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { // 1. 删除数据源对应的数据 self.yourDataSourceArray.remove(at: indexPath.row) // 2. 删除tableView中的行 self.tableView.deleteRows(at: [indexPath], with: .automatic) // 3. 退出编辑模式 self.tableView.setEditing(false, animated: true) } }
// Objective-C示例 - (void)handleLongPress:(UILongPressGestureRecognizer *)gesture { if (gesture.state != UIGestureRecognizerStateBegan) return; UITableViewCell *cell = (UITableViewCell *)gesture.view; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; if (!indexPath) return; // 进入编辑模式 [self.tableView setEditing:YES animated:YES]; // 延迟执行删除 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 删除数据源 [self.yourDataSourceArray removeObjectAtIndex:indexPath.row]; // 删除行 [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; // 退出编辑模式 [self.tableView setEditing:NO animated:YES]; }); }
优化小细节
- 如果你的tableView有其他长按手势(比如拖拽排序),记得设置手势的
delegate处理冲突; - 可以根据需求调整动画时长和删除触发的延迟时间,让交互更顺滑;
- 真机测试时注意iOS 10的手势响应优先级,避免和其他交互冲突。
内容的提问来源于stack exchange,提问作者SRIRAM




