gpt4 book ai didi

swift - 无法在 IOS10 中锁定一个 View Controller 的旋转

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:34 24 4
gpt4 key购买 nike

背景

我有一个应用程序使用 AVFoundation 来拥有自定义相机。这发生在 OCRViewController 中。当我拍照时,我将拍摄的照片发送到不同的 View ImagePreviewViewController

我正在使用 Xcode 10.2.1 (10E1001)Swift 5

目标

我想要实现的是将 ImagePreviewViewController 的方向锁定为图像的原始方向。我已经知道如何获取图像的方向,但无法锁定 View 的方向。

我这样得到图像旋转: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

https://www.hackingwithswift.com/example-code/uikit/how-to-lock-a-view-controllers-orientation-using-supportedinterfaceorientations

阅读 https://developer.apple.com/documentation/uikit/uiviewcontroller#//apple_ref/occ/instm/UIViewController/supportedInterfaceOrientationsHandling View Rotation 文档说明如下:

我在编写此查询时也尝试了很多建议的解决方案,但是,大多数人似乎使用了以下方法(或其变体),它对我不起作用。

override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}

override func shouldAutorotate() -> Bool{
return false
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return UIInterfaceOrientation.Portrait
}

As of iOS 8, all rotation-related methods are deprecated. Instead, rotations are treated as a change in the size of the view controller’s view and are therefore reported using the viewWillTransition(to:with:) method.

但是,我不确定如何从这里取得进展。

有趣的代码片段

下面的方法在我的OCRViewController中,这里我实例化ImagePreviewViewController并附上捕获的图像。

func displayCapturedPhoto(capturedPhoto : UIImage) {
let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "ImagePreviewViewController") as! ImagePreviewViewController
imagePreviewViewController.capturedImage = capturedPhoto
navigationController?.pushViewController(imagePreviewViewController, animated: true)
}

在我的 ImagePreviewViewController 中使用以下覆盖函数,我能够检测 View Controller 的方向。

override func viewDidAppear(_ animated: Bool) {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}

最佳答案

要限制一个屏幕的旋转,请使用它。

在 AppDelegate 中

var restrictRotation = Bool()

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if !restrictRotation {
return .portrait
} else {
return .all
}
}

在你的 View Controller 中添加函数,

func restrictRotation(restrict : Bool) -> Void {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.restrictRotation = restrict
}

在ViewDidload()方法中,调用禁用旋转的函数。

    self.restrictRotation(restrict: false)

在 viewWillDisappear() 方法中,调用启用旋转的函数。

    self.restrictRotation(restrict: true)

关于swift - 无法在 IOS10 中锁定一个 View Controller 的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com