Tapgesture for UIImageview inside table header view not working

25 views Asked by At

What am i doing wrong? I also tried to subclass UIView and put the 'button' (imageview) in that and use that as my headerview but still tapping doesn't work. Also tried using UITableHeaderFooterView.

lazy var groupDetailsButton: UIImageView = {
    let imageView = UIImageView()
    imageView.isUserInteractionEnabled = true
    let image = UIImage(named: "details") //?.resizedImage(newWidth: 30)
    imageView.image = image!.withRenderingMode(.alwaysTemplate)
    imageView.backgroundColor = .blue
    imageView.tintColor = .white
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFill
    imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(showGroupDetails)))
    return imageView
}()


func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(x: 0, y: 50, width: tableView.frame.width, height: 50))
    headerView.isUserInteractionEnabled = true
    headerView.addSubview(groupDetailsButton)
    headerView.isUserInteractionEnabled = true
    headerView.addConstraintsWithFormat("V:|-10-[v0(30)]", views: groupDetailsButton)
    headerView.addConstraintsWithFormat("H:[v0(30)]|", views: groupDetailsButton)
    return headerView
}


@objc func showGroupDetails(){
    print("SHOW GROUP DETAILS")
    let groupDetailsController = GroupDetailsController()
    groupDetailsController.groupDetails = groupDetails
    groupDetailsController.modalPresentationStyle = .fullScreen
    self.present(groupDetailsController, animated: true, completion: nil)
}
    
2

There are 2 answers

0
caa5042 On

This is very silly and i wasted a day trying to figure out what was wrong. but i was using UIGestureRecognizer instead of UITapGestureRecognizer.

1
DonMag On

You added a UIGestureRecognizer ... instead of a UITapGestureRecognizer recognizer.

Change this line:

imageView.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(showGroupDetails)))

to this:

imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showGroupDetails)))