Reputation: 19
In my swift code below it features a button in a tableview cell. The problem is when i click on the button nothining is being printed. I dont know what to do next the button is connected and should work. My code does not use storyboard its all code. So there is not a storyboard connection issue
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
let names = ["Katy Perry", "Jessica Biel", "Taylor Swift"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
let name = names[indexPath.row]
cell.textLabel?.text = name
cell.button.tag = indexPath.row // Set tag to identify which button is tapped
cell.button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
return cell
}
@objc func buttonTapped(_ sender: UIButton) {
let index = sender.tag
let selectedName = names[index]
print("Button tapped in cell for \(selectedName)")
}
}
class CustomTableViewCell: UITableViewCell {
let button = UIButton(type: .system)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
button.setTitle("Tap", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerYAnchor.constraint(equalTo: centerYAnchor),
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func buttonAction() {
print("Button in cell tapped")
}
}
Upvotes: 1
Views: 56
Reputation: 1319
Set isUserInteractionEnabled
to false
on the cell's contentView
, either in the cell's init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
or in the table view's func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.contentView.isUserInteractionEnabled = false
...
}
}
or
class CustomTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
...
contentView.isUserInteractionEnabled = false
...
}
}
Output:
Button in cell tapped
Button tapped in cell for Katy Perry
Upvotes: -1