繁体   English   中英

使用 Combine 和 Swiftui 重置 TextField 值

[英]Reset TextField value using Combine and Swiftui

我尝试在满足特定条件时重置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)
    }
}

这是您不需要任何组合的情况。 只需使用普通的didSet来观察属性的变化:

class ViewModel: ObservableObject {
    @Published var code = "" {
        didSet {
            if code.count == 4 {
                self.code = ""
            }
        }
    }
}

添加.receive(on: DispatchQueue.main)似乎可以解决此问题,但是,我不确定为什么需要它。

附带说明一下,确保在接收器块中捕获 [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.

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