Swift - How can I make an image full screen when c

2019-03-08 11:10发布

问题:

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.

回答1:

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()
}