代码之家  ›  专栏  ›  技术社区  ›  Erent

在uitableviewcell中调用多个按钮

  •  -1
  • Erent  · 技术社区  · 6 年前

    我有一个带有4个按钮的xib文件,每个按钮都有一个在单击时必须启动的功能。函数必须获取数据,在获取数据之后,它应该执行segue。我只能使用uitableviewcell类型的nib,并在viewcontroller内的tableview中显示它。

    在tableviewcell中点击时,是否可以让每个按钮都启动所需的功能,如果是,我该如何操作。

    我已经看了好几天类似于我的问题,尝试了所有建议的解决方案,但都不起作用。

    enter image description here

    Show ViewController from XIB-file-Button - Swift

    Perform segue from button in XIB

    Swift - Segue from Button inside a cell

    执行xib中的segue from按钮

    Perform Segue from Xib programmatically

    1 回复  |  直到 6 年前
        1
  •  1
  •   cnotethegr8    6 年前

    当然,在代码中让事件在操作中传递,然后访问索引路径非常简单。

    首先将目标添加到按钮。

    button.addTarget(self, action: #selector(someAction(_:event:)), for: .touchUpInside)
    

    然后使用此代码开始操作。

    @objc func someAction(_ button: UIButton, event: UIEvent) {
        guard let location = event.allTouches?.first?.location(in: tableView),
            let indexPath = tableView?.indexPathForItem(at: location)
            else {
                return
        }
    
        // TODO: fetch data
    
        performSegue(withIdentifier: "mySegueID", sender: button)
    }
    

    另外,如果您的数据是异步的,则可以使用PromiseKit之类的工具。 https://github.com/mxcl/PromiseKit