SwiftUI Repaint View Components on Device Rotation

后端 未结 12 1870
谎友^
谎友^ 2020-12-01 01:00

How to detect device rotation in SwiftUI and re-draw view components?

I have a @State variable initialized to the value of UIScreen.main.bounds.width when the first

12条回答
  •  离开以前
    2020-12-01 01:51

    It's easy to go without notifications, delegation methods, events, changes to SceneDelegate.swift, window.windowScene.interfaceOrientation and so on. try running this in simulator and rotating device.

    struct ContentView: View {
        let cards = ["a", "b", "c", "d", "e"]
        @Environment(\.horizontalSizeClass) var horizontalSizeClass
        var body: some View {
            let arrOfTexts = {
                ForEach(cards.indices) { (i) in
                    Text(self.cards[i])
                }
            }()
            if (horizontalSizeClass == .compact) {
                return VStack {
                    arrOfTexts
                }.erase()
            } else {
                return VStack {
                    HStack {
                        arrOfTexts
                    }
                }.erase()
            }
        }
    }
    
    extension  View {
        func erase() -> AnyView {
            return AnyView(self)
        }
    }
    

提交回复
热议问题