UIButton function will not respond when called in a UITableView cell

54 Views Asked by At

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?

2

There are 2 best solutions below

1
son On BEST ANSWER

As @HangaRash said on their comment, you should add button in cell's contentView, it will be:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    ...
    //addSubview(button)
    contentView.addSubview(button)
}

This is different from view hierarchy:

  1. addSubview(button)
UITableView
     |---MyCustomCell
             |--- UIButton (Get to it)
             |--- UITableViewCellContentView

//The button is below UITableViewCellContentView so the cell 
//will receive touch event from `didSelectRowAt` delegate.
  1. contentView.addSubview(button)
UITableView
     |---MyCustomCell
             |--- UITableViewCellContentView
                              |--- UIButton (Get to it)

//The button is above UITableViewCellContentView so the cell 
//will receive touch event from UIButton's first if within its frame.
//And receives `didSelectRowAt` delegate if out of button frame.
0
Izaan Saleem On

You can achieve this by using protocol and delegate method.

Click on this link for detailed answer => How to UITableView Click image and title