简体   繁体   English

SwiftUI onAppear 在尝试读取 UIKit 的 UIDevice 方向时无法正常工作

[英]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使用iOS14.4.2、Swfit5.3.2、XCode12.4,物理设备=iPhoneXS

On appearing, I am trying to write the current device orientation into a Static property and later use it inside a View.出现时,我试图将当前设备方向写入 Static 属性,然后在视图中使用它。

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.请注意, isPortrait总是false的——无论我在启动时如何定位我的 iPhone。 Especially, when the iPhone is in Portrait at startup, shouldn't the property be true ??特别是当 iPhone 在启动时处于 Portrait 状态时,该属性不应该是true吗?

Why this strange behaviour?为什么会出现这种奇怪的行为?

Apple should intensify device-orientation issues with SwiftUI, I think.我认为,Apple 应该通过 SwiftUI 来加强面向设备的问题。

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).请不要告诉我改用GeometryReader ,因为这在 iPad 上不起作用(还)。

Use this one:使用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM