[英]Reset TextField value using Combine and Swiftui
I try to reset a TextField
value when a certain condition is met (.count == 4)
, but it does not work, what am I missing?我尝试在满足特定条件时重置TextField
值(.count == 4)
,但它不起作用,我错过了什么?
class ViewModel: ObservableObject {
@Published var code = ""
private var anyCancellable: AnyCancellable?
init() {
anyCancellable = $code.sink { (newVal) in
if newVal.count == 4 {
self.code = ""
}
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
TextField("My code", text: $viewModel.code)
}
}
This is a case where you don't need any Combine.这是您不需要任何组合的情况。 Just use the normal didSet
to observe changes to the property:只需使用普通的didSet
来观察属性的变化:
class ViewModel: ObservableObject {
@Published var code = "" {
didSet {
if code.count == 4 {
self.code = ""
}
}
}
}
Adding .receive(on: DispatchQueue.main)
seems to fix this issue, however, I am not entirly sure why it is needed.添加.receive(on: DispatchQueue.main)
似乎可以解决此问题,但是,我不确定为什么需要它。
On a side note, make sure you capture [weak self] in a sink block to avoid memory leaks:附带说明一下,确保在接收器块中捕获 [weak self] 以避免 memory 泄漏:
anyCancellable = $code
.receive(on: DispatchQueue.main) // <--
.sink { [weak self] newVal in
if newVal.count == 4 {
self?.code = ""
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.