SwiftUI @State var initialization issue

前端 未结 3 1788
梦毁少年i
梦毁少年i 2020-11-30 01:57

I would like to initialise the value of an @State var in SwiftUI trough the init() method of a Struct, so it can take the proper text

相关标签:
3条回答
  • 2020-11-30 02:01

    SwiftUI doesn't allow you to change @State in the initializer but you can initialize it.

    Remove the default value and use _fullText to set @State directly instead of going through the property wrapper accessor.

    @State var fullText: String // No default value of ""
    
    init(letter: String) {
        _fullText = State(initialValue: list[letter]!)
    }
    
    0 讨论(0)
  • 2020-11-30 02:15

    The answer of Bogdan Farca is right for this case but we can't say this is the solution for the asked question because I found there is the issue with the Textfield in the asked question. Still we can use the init for the same code So look into the below code it shows the exact solution for asked question.

    struct StateFromOutside: View {
        let list = [
            "a": "Letter A",
            "b": "Letter B",
            // ...
        ]
        @State var fullText: String = ""
    
        init(letter: String) {
            self.fullText = list[letter]!
        }
    
        var body: some View {
            VStack {
                Text("\(self.fullText)")
                TextField("Enter some text", text: $fullText)
            }
        }
    }
    

    And use this by simply calling inside your view

    struct ContentView: View {
        var body: some View {
            StateFromOutside(letter: "a")
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:16

    I would try to initialise it in onAppear.

    struct StateFromOutside: View {
        let list = [
            "a": "Letter A",
            "b": "Letter B",
            // ...
        ]
        @State var fullText: String = ""
    
        var body: some View {
            TextField($fullText)
                 .onAppear {
                     self.fullText = list[letter]!
                 }
        }
    }
    

    Or, even better, use a model object (a BindableObject linked to your view) and do all the initialisation and business logic there. Your view will update to reflect the changes automatically.


    Update: BindableObject is now called ObservableObject.

    0 讨论(0)
提交回复
热议问题