首页 文章

滑动以删除单元格不会取消UIButton操作

提问于
浏览
5

我的 UITableView 已启用滑动删除功能 . 每个单元格上都有 UIButton 执行操作(在这种情况下,执行segue) .

我希望如果我通过触摸按钮来滑动单元格,按钮的动作将被取消/忽略,并且只会轻扫滑动 . 然而,实际发生的是检测和处理两种手势(轻扫轻击) .

这意味着如果我只想删除一个单元格并通过触摸按钮“意外”滑动,则应用程序将转到下一个屏幕 .

在这种情况下,如何强制我的应用忽略点击?

4 回答

  • 9

    对我来说,八月的回答非常好,但我想出了如何让它变得更好:

    检查表是否处于编辑模式以确定按钮是否应该执行其操作将使其按预期运行,但在用户体验中仍会存在问题:

    如果用户想要退出编辑模式,他应该能够点击单元格中的任何位置来实现该功能,包括按钮 . 但是,应用程序仍会首先分析 UIButton 的操作,点击该按钮不会退出编辑模式 .

    我找到的解决方案是在进入编辑模式时禁用按钮的用户交互,并在完成后重新启用它:

    // View with tag = 1 is the UIButton in question
    - (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
      [(UIButton *)[[tableView cellForRowAtIndexPath:indexPath] viewWithTag:1] setUserInteractionEnabled:NO];
    }
    
    - (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
      [(UIButton *)[[tableView cellForRowAtIndexPath:indexPath] viewWithTag:1] setUserInteractionEnabled:YES];
    }
    

    这样,拖动按钮进入编辑模式将不会触发按钮的操作,而将其按下以退出编辑模式将确实退出编辑模式 .

  • 2

    只要单元格进入编辑模式,一种优雅的方法是忽略按钮点击 . 这是有效的,因为滑动删除手势将导致在调用按钮点击操作之前调用willBeginEditingRowAtIndexPath .

    - (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
    {
        self.isEditing = YES;
    }
    
    - (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
    {
        self.isEditing = NO;
    }
    
    // button tapped
    - (IBAction)tap:(id)sender
    {
        if (self.isEditing) {
            NSLog(@"Ignore it");
        }
        else {
            NSLog(@"Tap");
            // perform segue
        }
    }
    
  • 2

    也可以在你的单元格的子类中执行它:

    override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
    
        actionButton?.userInteractionEnabled = !editing
    }
    
  • 0

    因为从按下按钮调用我的函数是我的主 UITableViewController 类的委托并且作为IBAction连接到 UITableViewCell ,我的 UITableViewCell 中的按钮仍然在按下了 UIButton 作为滑动的一部分按下的滑动 .

    为了阻止我使用相同的 UITableView 委托作为接受的答案,但必须设置文件级变量来监视是否正在进行编辑 .

    // in custom UITableViewCell class
    @IBAction func displayOptions(_ sender: Any) {
        delegate?.buttonPress()
    }
    
    // in UITableViewController class that implemented delegate
    fileprivate var cellSwiped: Bool = false
    
    func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
        cellSwiped = true
    }
    
    func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
        cellSwiped = false
    }
    
    func displayContactsSheet(for contact: Contact) {
        if cellSwiped {
            return
        }
        // proceed with delegate call button press actions
    }
    

相关问题