Swift - How can I make an image full screen when clicked and then original size when clicked again?

Tessa picture Tessa · Jan 9, 2016 · Viewed 35.4k times · Source

For the app that I am making I want the user to be able to click an image to make it full screen on the app. And then the user to be able to click the now full screen image to make it the original size.

Is this possible?

Any help would be great, I am just a beginner learner on xcode and am interested in knowing how to do this.

Answer

vacawama picture vacawama · Jan 9, 2016

Here is code which creates a full screen image (with black bars to preserve aspect ratio) when an image is clicked.

To use this, add this code to your ViewController which holds the image.

Then, for your imageView that you want to expand, check the box for userInteractionEnabled in the Attributes Inspector, and add a TapGestureRecognizer to it and set it call imageTapped.

@IBAction func imageTapped(sender: UITapGestureRecognizer) {
    let imageView = sender.view as! UIImageView
    let newImageView = UIImageView(image: imageView.image)
    newImageView.frame = UIScreen.main.bounds
    newImageView.backgroundColor = .blackColor()
    newImageView.contentMode = .ScaleAspectFit
    newImageView.userInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: "dismissFullscreenImage:")
    newImageView.addGestureRecognizer(tap)
    self.view.addSubview(newImageView)
    self.navigationController?.isNavigationBarHidden = true
    self.tabBarController?.tabBar.isHidden = true
}

func dismissFullscreenImage(sender: UITapGestureRecognizer) {
    self.navigationController?.isNavigationBarHidden = false
    self.tabBarController?.tabBar.isHidden = false
    sender.view?.removeFromSuperview()
}

This code works by creating a new fullscreen image which covers everything else. It has its own TapGestureRecognizer that removes the fullscreen image from its superView (and thus uncovers the original screen).


Update for Swift 3 and 4:

@IBAction func imageTapped(_ sender: UITapGestureRecognizer) {
    let imageView = sender.view as! UIImageView
    let newImageView = UIImageView(image: imageView.image)
    newImageView.frame = UIScreen.main.bounds
    newImageView.backgroundColor = .black
    newImageView.contentMode = .scaleAspectFit
    newImageView.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
    newImageView.addGestureRecognizer(tap)
    self.view.addSubview(newImageView)
    self.navigationController?.isNavigationBarHidden = true
    self.tabBarController?.tabBar.isHidden = true
}

@objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
    self.navigationController?.isNavigationBarHidden = false
    self.tabBarController?.tabBar.isHidden = false
    sender.view?.removeFromSuperview()
}