Keyboard will not show when setting focus on a SwiftUI text field from a button in an ornament on visionOS

Using a button that is placed in the bottom ornament to set focus on a text field will not display the keyboard properly while a button embedded in the view will behave as expected.

To demonstrate the issue, simply run the attached project on Vision Pro with visionOS 1.1 and tap the Toggle 2 button in the bottom ornament. You’ll see that the field does have focus but the keyboard is now visible.

Run the same test with Toggle 1 and the field will get focus and the keyboard will show as expected.

import SwiftUI
import RealityKit
import RealityKitContent

struct ContentView: View {
    @State private var text = ""
    @State private var showKeyboard = false
    
    @FocusState private var focusedField: FocusField?
    
    private enum FocusField: Hashable {
        case username
        case password
    }
    
    var body: some View {
        VStack {
            TextField("Test", text: $text)
                .focused($focusedField, equals: .username)
            
            Text("Entered Text: \(text)")
                .padding()
            
            Button("Toggle 1") { // This button will work and show the keyboard
                if focusedField != nil {
                    focusedField = nil
                } else {
                    focusedField = .username
                }
            }
            
            Spacer()
        }
        .padding()
        .toolbar {
            ToolbarItem(placement: .bottomOrnament) {
                Button("Toggle 2") { // This button will set focus properly but not show the keyboard
                    if focusedField != nil {
                        focusedField = nil
                    } else {
                        focusedField = .username
                    }
                }
            }
        }
    }
}

Is there a way to work around this?

FB13641609

Keyboard will not show when setting focus on a SwiftUI text field from a button in an ornament on visionOS
 
 
Q