SwiftUI @State var initialization issue

前端 未结 3 1812
梦毁少年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: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.

提交回复
热议问题