标签: portrait

  • SwiftUI 如何让view强制支持横屏或竖屏

    问题:有时候在编写APP时,我们会需要某个页面只支持手机的某个方向(并不是懒得适配,确信)。而在swiftUI中,要实现这个设定又变得更加复杂了,本篇文章就希望提供一个清晰且简单的解法,来支持这一点。

    首先,我们需要swiftUI支持AppDelegate.

    在非swiftUI中,这个文件是在创建项目的时候就会被系统一同创建的,但swiftUI并没有为我们创建这个文件,但这并不意味着swiftUI就无法连接到AppDelegate并作出响应

    而其实建立连接也十分简单,首先,创建一个class,这里其实创建AppDelegate的任何方法都可以,但为了不重复赘述,我这里直接写好了后面屏幕方向设定会用到的方法
    [code language=”objc”]
    class AppDelegate: NSObject, UIApplicationDelegate {
    static var orientationLock = UIInterfaceOrientationMask.portrait

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return AppDelegate.orientationLock
    }
    }
    [/code]
    这个设定,是将APP支持的屏幕方向设置了只支持竖屏,当然,如果你的APP也仅仅想做到这一步,那其实在设置里也可以直接做到,不用专门写一个class

    接下来,在某个我们希望只支持横屏的view中,只要写下如下代码,即可切换到横屏
    [code language=”objc”]
    import SwiftUI

    struct DestinationView: View {

    var body: some View {
    Group {

    Text("Hello")

    }.onAppear {
    AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
    UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
    UINavigationController.attemptRotationToDeviceOrientation()
    }
    .onDisappear {
    DispatchQueue.main.async {
    AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    UINavigationController.attemptRotationToDeviceOrientation()
    }
    }
    }
    }
    [/code]
    要注意的是,UIDevice中设定Value时要使用rawValue,否则会报错,而在onDisappear方法中,要使用异步来保证当前view消失时,不会因为之前的view的屏幕朝向不同而报错