How do I access data from a child view as the parent view at any time in SwiftUI?

前端 未结 3 1383
暗喜
暗喜 2021-01-13 13:00

I\'m new to SwiftUI and understand that I may need to implement EnvironmentObject in some way, but I\'m not sure how in this case.

This is the Trade cla

3条回答
  •  自闭症患者
    2021-01-13 13:45

    You can use @Binding and @State / @Published in Combine. In other words, use a @Binding property in Child View and bind it with a @State or a @Published property in Parent View as following.

    struct ChildView: View {
        @Binding var property1: String
        var body: some View {
            VStack(alignment: .leading) {
                TextField(placeholderTitle, text: $property1)
            }        
        }
    }
    struct PrimaryTextField_Previews: PreviewProvider {
        static var previews: some View {
            PrimaryTextField(value: .constant(""))
        }
    }
    
    struct ParentView: View{
        @State linkedProperty: String = ""
        //...
            ChildView(property1: $linkedProperty)
        //...
    }
    

    or if you have a @Publilshed property in your viewModel(@ObservedObject), then use it to bind the state like ChildView(property1: $viewModel.publishedProperty).

提交回复
热议问题