美文网首页SwiftUI
SwiftUI一起学之八 -- 横竖屏切换

SwiftUI一起学之八 -- 横竖屏切换

作者: sunny_ke_ke | 来源:发表于2021-05-24 10:10 被阅读0次

一 学习目标

在SwiftUI中切换横竖不同的布局

二 学习效果

image.pngimage.png image.pngimage.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()
    }
}

相关文章

网友评论

    本文标题:SwiftUI一起学之八 -- 横竖屏切换

    本文链接:https://www.haomeiwen.com/subject/lbtxsltx.html