Ios 当用户在Swift中点击我的UIImage时,如何在全屏上显示图像?

Ios 当用户在Swift中点击我的UIImage时,如何在全屏上显示图像?,ios,swift,uiimage,Ios,Swift,Uiimage,我正在我的应用程序中显示一张照片,我正在使用UIImage。到目前为止,我是这样做的: func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in

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

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组件时全屏显示照片的内容?

您需要的是在requestPhoto图像视图中添加UIAppgestureRecognitor。大概是这样的:

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

self.requestPhoto.addGestureRecognizer(tapGestureRecognizer)
self.requestPhoto.userInteractionEnabled = true
最后一行是需要的,因为UIImageView在默认情况下已将其打开,因此触摸将被取消

然后在同一个班级:

func tapHandler(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
         // change the size of the image view so that it fills the whole screen
    }
}
整个过程还可以受益于一个标志,表明视图是否为全屏,这样当用户点击全屏图像时,您就可以反转过程

和往常一样,您可以在中阅读更多内容。

如何在iOS上将缩略图照片放大为全屏照片视图

我通过创建具有相同图像的新UIImageView对象并将其帧设置为缩略图图像解决了此问题:

let fullscreenPhoto = UIImageView(frame: thumbnailImage.frame)
然后将图像作为子层添加到主窗口:

UIApplication.sharedApplication().windows.first!.addSubview(fullscreenPhoto)
使用块通过动画进行大小调整:

let windowFrame = UIApplication.sharedApplication().windows.first!.frame
UIView.animateWithDuration(0.4, delay: 0.0, options: .CurveEaseInOut, animations: {

            fullscreenPhoto.frame = windowFrame
            fullscreenPhoto.alpha = 1
            fullscreenPhoto.layoutSubviews()

            }, completion: { _ in
        })
您可以在此处找到现成的解决方案:

提供了用于全屏显示和隐藏的手势识别器。
您只需将UIImageView设置为故事板中的SLImageView类,所有魔术就完成了。

如果大小小于视图大小,图像将拉伸。嘿,感谢您的评论,我想在现在显示图像时显示图像。但是另外,我想让用户在点击图像时可以全屏显示图像预览。嘿,谢谢你,但是我试过了,它不起作用。。。我在viewDidLoad中添加了前两行,在我的类中的其他地方添加了其余的行,但当我点击它时仍然没有效果。可能还剩下什么吗?是的,我实际上忘记了一件事-图像视图的userInteractionEnabled设置为false,这会阻止触摸被转发到手势识别器。只需在viewDidLoad中添加self.requestPhoto.userInteractionEnabled=true,就可以了。我还将此添加到了答案中。谢谢,在我的例子中,它起作用了:让TapGestureRecognitzer=UITapGestureRecognitzerTarget:self,action:tapHandler:,不知怎的,当我使用action:SelectortapHandler时,它抛出了无法识别的选择器。。。但是现在它工作了,谢谢你的帮助!还有一件事@Losiowaty-我在这里补充了一个后续问题,你能看一下吗?也许你能帮助我,谢谢!