ios – UIButton function will not respond when called in a UITableView cell


I have a UITableView and I have also defined a subclass of it to include a button in each of my cells.
In order to check that its functionality works properly I have defined an @objc function (since I am doing it programmatically).

I can see the tables cells are present as well as the button visible inside it as I already registered it in the viewDidLoad function of my UIViewController class, but when I click it it does not respond. I am expecting to get a message printed in the console

 @objc func actbuttonFuncCall(_ sender: UIButton) {
        print("button clicked")
    }

This how I defined the tableView function for the cellForRowAt section:

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) as! MyCustomCell

           if let model = viewsArray[indexPath.row] {
               // name  assinged from another VC
                   cell.textLabel?.text = model.name
               cell.textLabel?.textColor = .systemPink
               
               cell.button.isUserInteractionEnabled = true
               cell.isUserInteractionEnabled = true
               cell.button.addTarget(self, action: #selector(actbuttonFuncCall), for: .touchUpInside)

               }
         
           return cell
       }

And this is the subclass for my UIButton

class MyCustomCell: UITableViewCell {
    let button = UIButton()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        button.setTitle("Get to it", for: .normal)
                button.backgroundColor = .blue
        addSubview(button)
        
        button.translatesAutoresizingMaskIntoConstraints = false
               NSLayoutConstraint.activate([
                   button.centerYAnchor.constraint(equalTo: centerYAnchor),
                   button.centerXAnchor.constraint(equalTo: centerXAnchor),
                   button.widthAnchor.constraint(equalToConstant: 100), // Adjust as needed
                   button.heightAnchor.constraint(equalToConstant: 40)  // Adjust as needed
               ])
      
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I there any other action I should perform to make my button functionality work?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img