【发布时间】:2019-11-18 16:47:18
【问题描述】:
背景
我有一个使用 AVFoundation 的应用程序,以便拥有一个自定义相机。这发生在OCRViewController。当我拍照时,我会将捕捉到的照片发送到不同的视图ImagePreviewViewController。
我正在使用Xcode 10.2.1 (10E1001) 和Swift 5
目标
我想要实现的是将ImagePreviewViewController 的方向锁定为图像的原始方向。我已经知道如何获取图像的方向,但我无法锁定视图的方向。
我得到这样的图像旋转:let imageOri = capturedImage?.imageOrientation
我尝试了什么?
我在和其他几个来源尝试了接受的答案:
How to lock orientation just for one view controller?
How to lock orientation of one view controller to portrait mode only in Swift
在 Handling View Rotation 下阅读https://developer.apple.com/documentation/uikit/uiviewcontroller#//apple_ref/occ/instm/UIViewController/supportedInterfaceOrientations 的文档,说明如下:
在编写此查询时,我也尝试了许多建议的解决方案,但是,大多数似乎使用以下方法(或它的变体),它对我不起作用。
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}
override func shouldAutorotate() -> Bool{
return false
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return UIInterfaceOrientation.Portrait
}
从 iOS 8 开始,所有与旋转相关的方法都已弃用。相反,旋转被视为视图控制器视图大小的变化,因此使用 viewWillTransition(to:with:) 方法报告。
但是,我不确定如何从这里开始。
有趣的代码sn-ps
下面的方法在我的OCRViewController里,这里我实例化ImagePreviewViewController,并附上截取的图片。
func displayCapturedPhoto(capturedPhoto : UIImage) {
let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "ImagePreviewViewController") as! ImagePreviewViewController
imagePreviewViewController.capturedImage = capturedPhoto
navigationController?.pushViewController(imagePreviewViewController, animated: true)
}
使用ImagePreviewViewController 中的以下覆盖函数,我能够检测到视图控制器的方向。
override func viewDidAppear(_ animated: Bool) {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}
【问题讨论】:
-
我所做的是在
UIApplicationDelegate中。声明两个变量var shouldSupportAllOrientation = true和var orientationLock = UIInterfaceOrientationMask.portrait并在appDelegate 中使用supportedInterfaceOrientationsFor 返回orientationLock 变量。在您的视图控制器中appDelegate?.shouldSupportAllOrientation = trueappDelegate?.orientationLock = .portrait -
@KamalUpasena 我刚刚尝试过,但遗憾的是它不起作用。我也这样做了:在我的 AppDelegate 中,我按照您的指定创建了两个变量。然后在 viewWillAppear 下的视图控制器中(也尝试过 viewDidLoad)我像你一样使用它,无论额外的代码如何,视图仍然会旋转。
-
在 info.plist 中添加 4 项的方向支持
-
@KamalUpasena 你能详细说明一下吗?我不确定我是否理解这 4 项是什么。
-
从常规添加设备方向为纵向、上下颠倒、横向左、横向右 -> 部署信息
标签: swift xcode uiviewcontroller ios10 swift5