Search code examples
swiftuitapgesturerecognizer

AddGesture different in Swift 3?


I have no idea why my code isn't working :

let profileImageView: UIImageView = {
    let image = UIImageView()
    image.image = UIImage(named: "gameofthrones_splash")
    image.translatesAutoresizingMaskIntoConstraints = false
    image.contentMode = .scaleAspectFill
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    image.addGestureRecognizer(tapGesture)
    image.isUserInteractionEnabled = true

    return image
}()

This imageView is loaded in the ViewDidLoad (I can see it)

func handleSelectProfileImageView() {
    print("123")
}

But nothing get returned in the console when I'm tapping on it ! WTF?


Solution

  • It's in the target. This works when place in the viewDidLoad():

    profileImageView.frame = CGRect(x: 60, y: 60, width: 70, height: 70)
    view.addSubview(profileImageView)
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView))
    profileImageView.addGestureRecognizer(tapGesture)
    

    The target is "self", which is the UIViewController (not the UIImageView). In most cases (I'm sure there are outliers) you want to record a gesture in a view, but work with the gesture in a view controller.