SwiftUI @State var initialization issue

前端 未结 3 1811
梦毁少年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: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")
        }
    }
    

提交回复
热议问题