ios – SwiftUI – Set FocusState of TextField from outdoors


I’ve created a customized TextField to show and edit the title of things in my app. When a person creates a brand new merchandise I wish to focus this TextField robotically .onAppear so the title might be entered instantly. For present gadgets the TextField shouldn’t be centered.

Is the one method to do that to carry a @State outdoors of the CustomTextField like within the instance beneath? To me it appears there may be a extra elegant approach to obtain this with out creating one more @State.

This is a little bit of simplified instance code:

struct ContentView: View {
    @State var textual content: String = "Textual content"
    @State var focusOnAppear = false
    @State var itemID = ""

    var physique: some View {

        VStack {
            Button("+ New merchandise") {
                focusOnAppear = true
                itemID = "0"
            }
            Button("Present merchandise"){
                focusOnAppear = false
                itemID = "1"
            }
            Button("One other present merchandise"){
                focusOnAppear = false
                itemID = "2"
            }
        }

        CustomTextField($textual content, focusOnAppear: focusOnAppear)
            .body(width: 200, peak: 44)
            .id(itemID)
    }
}

struct CustomTextField: View {

    @Binding non-public var textual content: String
    @FocusState var isFocused: Bool

    var focusOnAppear = false

    init(_ textual content: Binding<String>, focusOnAppear: Bool) {
        self._text = textual content
        self.focusOnAppear = focusOnAppear
    }

    var physique: some View {
        TextField("", textual content: $textual content)
            .centered($isFocused)
            .foregroundColor(isFocused ? .pink : .main)
            .border(Colour.grey)
            .onAppear {
                if focusOnAppear {
                    DispatchQueue.foremost.asyncAfter(deadline: .now()+0.5) {
                        isFocused = true
                    }
                }
            }
    }
}

Leave a Reply