对于我正在制作的应用,我希望用户能够点击图片,使其在应用上全屏显示。然后用户可以单击现在的全屏图像使其成为原始大小。
这可能吗?
任何帮助都会很棒,我只是xcode的初学者,我有兴趣知道如何做到这一点。
答案 0 :(得分:78)
这是在单击图像时创建全屏图像(带有黑条以保持纵横比)的代码。
要使用此功能,请将此代码添加到保存图像的ViewController中。
然后,对于要展开的imageView,请选中属性检查器中 userInteractionEnabled 的复选框,然后添加 TapGestureRecognizer 它并将其设置为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()
}
此代码的工作原理是创建一个涵盖其他所有内容的新全屏图像。它有自己的 TapGestureRecognizer ,可以从superView中删除全屏图像(从而揭开原始屏幕)。
Swift 3和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()
}