我正在开发一个带有视频播放器的应用,我的整个结构只适用于纵向视图,除了这个视频播放器。我想仅为此视图启用横向旋转。但是我查看了很多论坛,每个答案都是在 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")
}
}
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscape)) { error in
// handle error
}