Home>
About the action of the button added to TableViewCell

After adding TableView and TableViewCell on Storyboard, added buttons and actions to TableViewCell with the following code.
In the next action, I want to change the background of the button. I want to write the button's own settings in code. What should I do?

Written code
func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath)->UITableViewCell {
        let cell = UITableViewCell (style: .subtitle, reuseIdentifier: "Cell")
        let button = UIButton ()
        SetUpButton (button)
        cell.contentView.addSubview (button)
        button.addTarget (self, action: #selector (self.buttonEvent (_:)), for: UIControl.Event.touchUpInside)
}
@objc func buttonEvent (_ sender: UIButton) {
       // code to be realized
}

I wrote the following to the code that I want to achieve // ​​above. However, button cannot be inherited.

Code I want to implement
@ objc func buttonEvent (_ sender: UIButton) {
       button.backgroundColor = UIColor.black
}

If i read other question sites, etc., it seems that you can do it with button definitions other than in TableViewCell.
Sorry for the ugly text.

  • Answer # 1

    senderwill send information about the button that was pressed,
    It's just a reference, so if you play with it, the button you press will change.

    @ objc func buttonEvent (_ sender: UIButton) {
           print ("tappedBtn: \ (sender)")
           sender.backgroundColor = UIColor.black
    }

    If it doesn't work, let me know if you see "tappedBtn Honalara" on the console.

Related articles