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
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)
}
}