如何使用 UILongPressGestureRecognizer 从 tableview 单元格按钮传递数据?

How do you pass data from tableview cell button with a UILongPressGestureRecognizer?

我的单元格中有一个按钮,如果用户按住一定时间,它将触发弹出窗口。我无法通过长按按钮传递单元格数据。

下面是我如何通过常规点击提交和传递数据...

cell.addButton.tag = (indexPath as NSIndexPath).row

cell.addButton.addTarget(self, action: #selector(Dumps.addAction(_:)), for: UIControl.Event.touchUpInside)

.

@IBAction func addAction(_ sender: Any) {
                
let tag = (sender as AnyObject).tag
            
let cell = tableView.cellForRow(at: IndexPath.init(row: tag!, section: 0)) as! DumpsCell01
        
codeData = cell.codeField.text! }

以上工作正常。


下面是我如何使用长按手势提交按钮。我认为它通过 _sender 传递 nil

cell.deleteButton.tag = (indexPath as NSIndexPath).row

let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(Dumps.deleteAction(_:)))

cell.deleteButton.addGestureRecognizer(longGesture)

.

@objc func deleteAction(_ sender: UIGestureRecognizer){

let tag = (sender as AnyObject).tag
                
let cell = tableView.cellForRow(at: IndexPath.init(row: tag!, section: 0)) as! DumpsCell01
    
cell.codeLabel.backgroundColor = UIColor.red }

如何通过这种方法传递数据?

您应该使用 UIButtontag 而不是像上面那样使用 UILongPressGestureRecognizer

func deleteAction(_ sender: UILongPressGestureRecognizer) {
    guard let tag = (sender.view as? UIButton)?.tag else { return }
    let cell = tableView.cellForRow(at: IndexPath(row: tag, section: 0)) as? DumpsCell01
    cell?.codeLabel.backgroundColor = .red
}

注意:在整个项目中,我也避免了强制展开,您也应该这样做。