通过编码 button/function in swift 发送数据

Sending data through coded button/function in swift

我有一个为 tableViewCell 页脚创建的按钮,我想在按下按钮时传递该部分,但是当我打印出该部分时,它是一个完全任意的数字,我如何传递 Int 部分什么时候按下按钮?

  func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
            
            
            let button = UIButton()
            button.setTitle("Add Set", for: .normal)
            button.backgroundColor = UIColor.lightGray
            button.layer.cornerRadius = 5
            button.addTarget(self, action: #selector(CurrentSessionVC.addSetPressed(section:)), for: .touchUpInside)
            
            return button
        }


    @objc func addSetPressed(section: Int){
            //prints 4349567072
        }

您可以使用 tag 属性(在任何 UIView 对象中可用)以及 addTarget(_:action:for:) 对所有 [=14] 对象可用的事实=] 对象,将发送者(这里是你的按钮实例)传递给选择器:

//...
let button = UIButton()
button.tag = section // or any other int
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
//...

@objc func buttonAction(_ sender: UIButton) {
    let section = sender.tag
}

您可以阅读有关目标-行动机制的更多信息here