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
Answers
As @HangaRash said on their comment, you should add button in cell’s contentView, it will be:
This is different from view hierarchy:
You can achieve this by using protocol and delegate method.
Click on this link for detailed answer => How to UITableView Click image and title