I'm adding a TapGestureRecognizer to an UIImageView at my custom TableViewCell but it's not calling its action. When I tap on the Image, it triggers the didSelectRowAt delegate method of tableview. I am not using any storyboard or .xib. I have done this a thousand times with UI created via .xib with no problems, but I don't understand why programmatically this does not work. Any idea?
At my custom TableViewCell:
var favButton = UIImageView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(favButton)
configureFavButton()
}
func set(stock: Stock) {
self.stock = stock
favButton.image = UIImage(systemName: "heart.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
}
func configureFavButton() {
// Creating constraints using SnapKit
favButton.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(10)
make.centerY.equalToSuperview()
make.height.width.equalTo(30)
}
favButton.isUserInteractionEnabled = true
favButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(removeFromFavorites)))
}
@objc func removeFromFavorites() {
guard let stock = stock else { return }
delegate?.removeFromFavorites(stock)
}
At my ViewController, when defining my cell at cellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FavoriteCell") as! FavoriteCell
cell.delegate = self
cell.set(stock: model.favorites[indexPath.row])
return cell
}
CodePudding user response:
You need to add the subView (favButton) to the cell's contentView rather than the view itself
contentView.addSubview(favButton)