微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI:如何在没有 AppDelegate 的情况下强制横向

如何解决SwiftUI:如何在没有 AppDelegate 的情况下强制横向

我正在制作带有视频播放器的应用程序,我的整个结构仅用于纵向视图,除了这个视频播放器。我想仅为此视图启用横向旋转。但是我已经访问了很多论坛,每个答案都是向 App Delegate 添加一些代码,而我没有。那我该怎么办。

解决方法

这里有一个演示。您可以通过调用函数 changeOrientation 将方向更改为您喜欢的方向。您还可以在完成后使用 .onReceive 反转方向更改。每次发生方向更改时都会调用 .onReceive,因此您可以反转您不喜欢的方向更改。
我知道这不是最佳的,但这是我在不使用大量 UIKit 和 AppDelegate 的情况下能找到的最好的。您可以使用 AppDelegate 以获得更好的结果(我认为)。

import SwiftUI
import UIKit

struct ContentView: View {
    
    private let rotationChangePublisher = NotificationCenter.default
        .publisher(for: UIDevice.orientationDidChangeNotification)
    @State private var isOrientationLocked = false
    
    var body: some View {
        VStack {
            Button("Change orientation") {
                if UIDevice.current.orientation.isPortrait {
                    changeOrientation(to: .landscapeLeft)
                } else {
                    changeOrientation(to: .portrait)
                }
            }.padding()
            
            Button("Orientation is \(isOrientationLocked ? "" : "NOT ")Locked to portrait-only") {
                isOrientationLocked.toggle()
            }.padding()
        }
        .font(.system(size: 17,weight: .semibold))
        .onReceive(rotationChangePublisher) { _ in
            // This is called when there is a orientation change
            // You can set back the orientation to the one you like even
            // if the user has turned around their phone to use another
            // orientation.
            if isOrientationLocked {
                changeOrientation(to: .portrait)
            }
        }
    }
    
    func changeOrientation(to orientation: UIInterfaceOrientation) {
        // tell the app to change the orientation
        UIDevice.current.setValue(orientation.rawValue,forKey: "orientation")
        print("Changing to",orientation.isPortrait ? "Portrait" : "Landscape")
    }
}

此外,请确保您事先允许使用不同的方向:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。