1

I have a button I created for a tableViewCell footer, and want to pass the section when the button is pressed, but when I print out the section, it is a completely arbitrary number, how can I pass the section Int when the button is pressed?

  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
        }
Noah Iarrobino
  • 1,435
  • 1
  • 10
  • 31

1 Answers1

2

You can use the tag property (that is available in any UIView object) and the fact that addTarget(_:action:for:), which is available to all UIControl objects, passes the sender (here your button instance) to the selector:

//...
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
}

You can read more about the Target-Action Mechanism here

Alladinian
  • 34,483
  • 6
  • 89
  • 91