Search code examples
iosswiftheadertableviewgesture

Add gesture for the imageView in tableView's Section Header


I want to implement a tableview with a header look like this. I want to implement a function that it segue to another view controller when i press the icon in this header. But it seems the gesture recognizer doesn't work. The recognizer would give no response at all

The header's code is here

  override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UITableViewHeaderFooterView(frame:CGRect(x: 0, y: 0, width: frameWidth, height: headerViewHeight))
        let iconOffset = CGPoint(x: 8, y: 8)
        let iconSize = CGSize(width: headerViewHeight-16, height: headerViewHeight-16)
        let imageView = UIImageView(frame: CGRect(origin: iconOffset, size: iconSize))
        imageView.image = UIImage(named: "HENRY")
        imageView.layer.cornerRadius = (headerViewHeight-16)/2
        imageView.layer.masksToBounds = true

        let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("iconTapGestureHandler:"))
//        tapRecognizer.cancelsTouchesInView = false
        tapRecognizer.numberOfTapsRequired = 1
        tapRecognizer.delegate = self
        imageView.addGestureRecognizer(tapRecognizer)

        headerView.addSubview(imageView)
        return headerView
}

However, the iconTapGestureHandler function wouldn't be triggered after a tap the image view.

I have also implement the delegate method.

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

the iconTapGestureHandler Function is as below

@IBAction func iconTapGestureHandler(sender:UIGestureRecognizer){
    println("in touch")
    let mainPageVC = MainPageTableViewController()
    mainPageVC.isMyself = false
    mainPageVC.isPushed = false
    self.navigationController?.pushViewController(mainPageVC, animated: true)
}

Solution

  • By default in UIImageView user interaction is disabled. So add

    imageView.userInteractionEnabled = true