How to detect one button in tableview cell

后端 未结 4 672
说谎
说谎 2020-11-28 16:14

How to detect one button in UITableviewCell, I have 10 UIButton in UITableViewCell, next when I click on UIButton then i

4条回答
  •  遥遥无期
    2020-11-28 16:52

    To detect a UIButton in a UITableViewCell, you can follow any of the below approaches:

    1. Use UIButton IBOutlets

    You can create an IBOutlet corresponding to each UIButton in the UITableViewCell and use those outlets to identify which button action is performed.

    Example:

    class CustomCell: UITableViewCell
    {
        @IBOutlet weak var button1: UIButton!
        @IBOutlet weak var button2: UIButton!
        @IBOutlet weak var button3: UIButton!
        @IBOutlet weak var button4: UIButton!
        @IBOutlet weak var button5: UIButton!
    
        @IBAction func onTapButton(_ sender: UIButton)
        {
            if sender === button1
            {
                //button1 specific code here
            }
            else if sender === button2
            {
                //button2 specific code here
            }
            //and so on..
        }
    }
    

    2. Use UIButton Tag property

    You can provide a tag value to each of the UIButton present in the UITableViewCell and then use that tag to identify the specific button.

    Example:

    class CustomCell: UITableViewCell
    {
        @IBAction func onTapButton(_ sender: UIButton)
        {
            if sender.tag == 1
            {
                //button1 has a tag = 1
                //button1 specific code here
            }
            else if sender.tag == 2
            {
                //button2 has a tag = 2
                //button2 specific code here
            }
            //and so on..
        }
    }
    

    Edit:

    For setting different images in selected/unselected state of UIButton, you can use storyboard for that:

    For Unselected state:

    For Selected state:

    Let me know if you still face any issues.

提交回复
热议问题