6

I am trying to set a default value in a text field but I don't know how.

//TextField("", text:$name)

struct MyView: View {

    @State var name:String = ""

    var body: some View {
        TextField("", text:$name)
    }

    init(n:String) {
        name = n
    }
}

If I call MyView("Jack"), Jack does not appear as a value in the textfield.

1 Answer 1

9

This can be done in a following way

struct MyView: View {

    @State var name: String

    var body: some View {
        TextField("", text:$name)
    }

    init(n: String) {
        _name = State(initialValue: n)
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Asperi Why does undescored var name works? And is there more vanilla way of assigning initial value?
@ЭлёржонКимсанов, Swift Property Wrappers
If anyone is wondering how this works, here someone actually explained this answer instead of code only: stackoverflow.com/a/61398097/1972372
this is interesting, any particular reason why should we use property wrappers to initialize? I mean wouldn't view updates as soon as the value is assigned in onAppear closure?(that's the whole point of @State)
Please be aware of the view identity implications of calling the state property's initializer. It is never a good idea to call it when the input is a variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.