'How do I make a text field focused when the sheet containing it appears

I want to show a sheet, and immediately put the text field inside in focus when the sheet is shown, so the user can immediately start typing without tapping on the sheet separately.

I have tried the solutions in this thread: https://developer.apple.com/forums/thread/681962

But none of them are working. Here's my current code:

struct MySheet: View {
    @State var text: String
    @FocusState var focusedField: FocusField?
    var body: some View {
        VStack {
            TextField("", text: $text)
                .focused($focusedField, equals: .field)
                .padding()
                .task {
                    self.focusedField = .field
                }
        }
    }
}

It seems like this should be very simple and a common use-case. How can I achieve this?



Solution 1:[1]

seem like you need to delay a bit before set focus on it

TextField("Text Field", text: $text)
    .focused($focusedField, equals: .field)
    .padding()
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
            self.focusedField = .field
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 meomeomeo