Search code examples
iosswiftuiviewcontrolleruiimageview

Is is possible to click an imageView and open a new View Controller?


I'm new to IOS and learning the IDE at the moment. I was wondering if its possible to link an imageView, when clicked, to a View Controller


Solution

  • Sure. First, in viewDidLoad of your UIViewController make it tappable:

    imageView.isUserInteractionEnabled = true
    

    Then assign the gesture recognizer:

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

    Once the action is triggered, perform a transition to a new VC:

    // Func in your UIViewController
    @objc func imageTap() {
        // present modally
        self.present(YourNewViewController())
        // or push to the navigation stack
        self.navigationController?.push(YourNewViewController())
        // or perform segue if you use storyboards
        self.preformSegue(...)
    }