iKK
iKK

Reputation: 7012

SwiftUI onAppear not working properly when trying to read UIKit's UIDevice orientation

Using iOS14.4.2, Swfit5.3.2, XCode12.4, physical device = iPhoneXS

On appearing, I am trying to write the current device orientation into a Static property and later use it inside a View.

However, the value is not correctly written when appearing.

Here is my code (see below)

Note that isPortrait will always be false - no matter how I orient my iPhone at startup. Especially, when the iPhone is in Portrait at startup, shouldn't the property be true ??

Why this strange behaviour ?

Apple should intensify device-orientation issues with SwiftUI, I think.

struct MyView: View {
  
    @State var isPortrait: Bool = true
 
    var body: some View {
    
        VStack {
            Text("text1")
            if isPortrait {
                Test("text2")      // never shown why ???
            }
        }
        .onAppear {
            isPortrait = (UIDevice.current.orientation == .portrait)
            print(isPortrait)  // always prints 'false' why ????
        }
    } 
}

And please, don't tell me to use GeometryReader instead since this does not work on iPad (yet).

Upvotes: 0

Views: 348

Answers (1)

Kuhlemann
Kuhlemann

Reputation: 3396

Use this one:

UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isPortrait

Upvotes: 1

Related Questions