一 学习目标
在SwiftUI中切换横竖不同的布局
二 学习效果
image.png image.png三 主要操作步骤
3.1 监听屏幕转动事件
//监听屏幕转动
Text(isLand ? "我现在是横屏" : "我现在是竖屏")
.onReceive(orientationPublisher) { _ in
let windowScene = UIApplication.shared.windows.first? .windowScene
self.isLand = windowScene?.interfaceOrientation.isLandscape ?? false
}
3.2 根据不同的屏幕事件显示不同的布局
Text(isLand ? "我现在是横屏" : "我现在是竖屏")
四 完整代码
import SwiftUI
import AlertToast
struct ContentView: View {
@State var isLand = false
let orientationPublisher = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
var body: some View {
Text(isLand ? "我现在是横屏" : "我现在是竖屏")
.onReceive(orientationPublisher) { _ in
let windowScene = UIApplication.shared.windows.first? .windowScene
self.isLand = windowScene?.interfaceOrientation.isLandscape ?? false
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
网友评论