简体   繁体   English

SwiftUI ViewModel 发布的属性和绑定

[英]SwiftUI ViewModel published property and binding

My question is probably the result of a misunderstanding but I can't figure it out, so here it is:我的问题可能是误解的结果,但我无法弄清楚,所以这里是:

When using a component like a TextField or any other component requiring a binding as input当使用像 TextField 这样的组件或任何其他需要绑定作为输入的组件时

TextField(title: StringProtocol, text: Binding<String>)

And a View with a ViewModel, I naturally thought that I could simply pass my ViewModel @Published properties as binding:还有一个带有 ViewModel 的 View,我自然认为我可以简单地将我的 ViewModel @Published属性作为绑定传递:

class MyViewModel: ObservableObject { 
     @Published var title: String
     @Published var text: String
}

// Now in my view
var body: some View {
    TextField(title: myViewModel.title, text: myViewModel.$text)
}

But I obviously can't since the publisher cannot act as binding.但我显然不能,因为发布者不能充当约束力。 From my understanding, only a @State property can act like that but shouldn't all the @State properties live only in the View and not in the view model?据我了解,只有@State属性可以这样做,但所有@State属性不应该只存在于视图中而不存在于视图model 中吗? Or could I do something like that:或者我可以做这样的事情:

class MyViewModel: ObservableObject { 
     @Published var title: String
     @State var text: String
}

And if I can't, how can I transfer the information to my ViewModel when my text is updated?如果我不能,当我的文本更新时,如何将信息传输到我的 ViewModel?

You were almost there.你快到了。 You just have to replace myViewModel.$text with $myViewModel.text .您只需将myViewModel.$text替换$myViewModel.text

class MyViewModel: ObservableObject {

    var title: String = "SwiftUI"

    @Published var text: String = ""
}

struct TextFieldView: View {

    @ObservedObject var myViewModel: MyViewModel = MyViewModel()

    var body: some View {
        TextField(myViewModel.title, text: $myViewModel.text)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM