一 学习目标
在SwiftUI中切换横竖不同的布局
二 学习效果
![image.png](https://img.haomeiwen.com/i901836/c6f7ca19dff726a7.png&originHeight=1366&originWidth=672&size=60103&status=done&style=none&width=336?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![image.png](https://img.haomeiwen.com/i901836/9ef4d73375b795c4.png&originHeight=672&originWidth=1378&size=65231&status=done&style=none&width=689?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
三 主要操作步骤
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()
}
}
网友评论