因为我的应用程序支持所有方向.我只想将肖像模式锁定到特定的UIViewController.

e、 g.假设它是选项卡式应用程序,当SignIn View以模式显示时,我只希望SignIn View处于纵向模式,无论用户如何旋转设备或当前设备方向如何

推荐答案

当您有一个复杂的视图层次 struct 时,事情可能会变得非常混乱,比如有多个导航控制器和/或选项卡视图控制器.

此实现将其置于各个视图控制器上,以设置它们希望锁定方向的时间,而不是依赖应用程序委托通过迭代子视图来查找方向.

Swift 3, 4, 5

在AppDelegate中:

/// set orientations you want to be allowed in this property by default
var orientationLock = UIInterfaceOrientationMask.all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
}

在其他一些全局 struct 或助手类中,我创建了AppUtility:

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
    
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
   
        self.lockOrientation(orientation)
    
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}

然后在所需的ViewController中,要锁定方向:

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    AppUtility.lockOrientation(.portrait)
    // Or to rotate and lock
    // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
    
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    // Don't forget to reset when view is being removed
    AppUtility.lockOrientation(.all)
}

If iPad or Universal App

Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor delegate will not get called if that is not checked. enter image description here

Swift相关问答推荐

您可以在SwiftUI中将transformEffect与scrollTransition一起使用吗?

通过withstickedContinuation传递通用类型T

在Swift中,是否只有iOS版本超过15才能导入Swift包?

并发访问SWIFT中数组的非重叠子范围

我正在try 通过代码设置节中页眉和页脚的高度,但它不起作用

如何增加 NSStatusBar 图像大小?

在 Swift 5.7 中使用协议作为类型时什么时候需要写 `any`

一组可散列的自定义元素插入相等的元素

swift 是否遇到 Java 的 2gb 最大序列化大小问题?

为 SwiftUI 中的属性提供默认值

如何在 SwiftUI 中将图像传递到 2 个视图

用户输入以更改通过点击生成的形状大小

来自数据的 SwiftUI 图像

如何让动画变慢 SwiftUI

SwiftUI 4 列表初始化程序在 iOS 中不可用

Vapor 4,如何按外键过滤?

从 Finder 打开文件时,SwiftUI 的应用程序(_ openFile:) 从未调用过

如何让 UIKit 挤压你的视图,使其适合屏幕

如何仅将 SwiftUI 不透明度应用于父视图?

如何在 Swift 中将 NSURL 转换为字符串