gre*_*en8 9 rotation ios swiftui
我正在制作带有视频播放器的应用程序,除了这个视频播放器之外,我的整个结构仅用于纵向视图。我想仅为该视图启用横向旋转。但我查过很多论坛,每个答案都是向 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")
}
}
Run Code Online (Sandbox Code Playgroud)
另外,请确保事先允许您想要使用的不同方向:
| 归档时间: |
|
| 查看次数: |
7679 次 |
| 最近记录: |