SwiftUI iOS 14 keyboard issues in orientation changes

Consider the following sample code

Code Block swift
import SwiftUI
struct ContentView: View {
    @State var text = ""
    @State var portrait = true
    func updateInterfaceOrientation() {
        guard let currentWindowScene = UIApplication.shared.connectedScenes.first(
                where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
            return
        }
        self.portrait = currentWindowScene.interfaceOrientation.isPortrait
    }
    var body: some View {
        ZStack {
            if portrait {
                VStack {
                    Spacer()
                    TextField("", text: $text)
                        .background(Color.gray)
                }
            } else {
                VStack {
                    Spacer()
                    TextField("", text: $text)
                        .background(Color.gray)
                }
            }
        }
        .onAppear(perform: updateInterfaceOrientation)
        .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            updateInterfaceOrientation()
        }
    }
}


Code is pretty straightforward and is the proposed way for SwiftUI's dynamic interfaces. IE: you double down on your elements, and the interface gets switched from one to the other.

Now this piece of code, compared to the one without the if portrait has multiple issues because of the keyboard.
  • When the portrait vs landscape gets changed, you lose the on-screen keyboard. I can kind-of live with that.

  • iOS 14: When you have a on-screen keyboard in portrait mode, and you move to landscape mode, the zone stays higher on screen, as if the keyboard was actually there, but it's not. If you move back to portrait mode, the safe zone becomes 3/4 of the screen. I cannot live with that!

Any clues? Happens with latest official and latest beta (.2)
I'm experiencing a similar issue: views stay higher on the screen as if the keyboard is still there but it is in fact not there, only in my case it's happening when navigate through the screens with a specific timing instead of changing orientation.
I was able to somewhat mitigate it with .ignoreSafeArea(.keyboard), but it requires an additional spacer which is unacceptable in production.
Interestingly Xcode is not able to capture view hierarchy when this happens.
Were you able to resolve this issue?

Honestly, lastcookie, I gave up. I removed any discrepancies in Portrait vs Landscape and gave up being fancy. It’s one of my grudges on SwiftUI: if you don’t follow the intents and purposes, and you are trying to be like a system app and follow good practices, it will mostly work, but not all the time.

SwiftUI iOS 14 keyboard issues in orientation changes
 
 
Q