【问题标题】:How do you pass data from tableview cell button with a UILongPressGestureRecognizer?如何使用 UILongPressGestureRecognizer 从 tableview 单元格按钮传递数据?
【发布时间】:2021-01-31 20:13:10
【问题描述】:

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

以下是我通过常规点击提交和传递数据的方式...

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 传递为零

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 }

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

【问题讨论】:

    标签: swift tableview


    【解决方案1】:

    您应该使用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
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多