本文介绍了当用户在 Swift 中点击我的 UIImage 时,如何全屏显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的应用程序中显示一张照片,我为此使用了 UIImage.到目前为止,我就是这样做的:

I'm displaying a photo in my app and I'm using UIImage for that. So far this is how I'm doing that:

func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        completion(data: data, response: response, error: error)
        }.resume()
}

func downloadImage(url: NSURL){
    getDataFromUrl(url) { (data, response, error)  in
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            print("Download Finished")
            self.requestPhoto.image = UIImage(data: data)
        }
    }
}

然后在 viewDidLoad() 我正在做:

if let checkedUrl = NSURL(string: photo) {
        requestPhoto.contentMode = .ScaleAspectFit
        downloadImage(checkedUrl)
    }

这让 UIImage 充满了我的照片,但它是不可点击的,它是原始组件的大小.有没有办法添加某种侦听器或当用户点击 UIImage 组件时可以全屏显示照片的东西?

That leaves the UIImage filled with my photo, but it's not clickable and it's the size of the original component. Is there a way of adding some kind of listener or something that will display the photo on fullscreen when user taps the UIImage component?

推荐答案

您需要的是将 UITapGestureRecognizer 添加到您的 requestPhoto 图像视图中.像这样:

What you need is to add a UITapGestureRecognizer to your requestPhoto image view. Something like this :

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapHandler"))

self.requestPhoto.addGestureRecognizer(tapGestureRecognizer)
self.requestPhoto.userInteractionEnabled = true

最后一行是必需的,因为 UIImageView 默认关闭了它,所以触摸被取消了.

The last line is needed as UIImageView has it turned of by default, so the touches get canceled.

然后在同一个班级:

func tapHandler(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
         // change the size of the image view so that it fills the whole screen
    }
}

整个事情也可以从一个标志中受益,说明视图是否全屏,这样当用户点击全屏图像时,你可以逆转这个过程.

The whole thing could also benefit from a flag saying if the view is fullscreen or not, so that when the user taps the fullscreen image you can reverse the process.

一如既往,您可以在 文档.

As always, you can read more in the docs.

这篇关于当用户在 Swift 中点击我的 UIImage 时,如何全屏显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 12:41