【问题标题】:How to solve deadlock on multiple Published on 2 TextField in SwiftUI?如何解决 SwiftUI 中多个 Published on 2 TextField 的死锁?
【发布时间】:2020-07-23 05:49:04
【问题描述】:

我的视图模型中有两种已发布状态,一种用于source,另一种用于destination

基于解决方案here 检测文本字段的实时变化。我是这样实现的

TextField("", text: $viewModel.source)
TextField("", text: $viewModel.destination)

问题,每当用户输入一些值时,我都需要更新这两个字段。例如 - 如果用户在 source 上输入,那么我需要使用源输入更新 destination。如果用户输入destination,则需要更新source

@Published var source: Double = 0 {
        didSet {
            destination = source / rate
        }
    }

这只是一种解决方案。我必须对目的地重复它,然后它会造成死锁

@Published var destination: Double = 0 {
        didSet {
            source = destination * rate
        }
    }

如何解决这个问题?唯一的解决方案是我想如果有任何方法可以以回调的形式进行实时更改,那么我可以更新任一字段,但我不知道是否有可能

【问题讨论】:

    标签: ios swiftui textfield publish combine


    【解决方案1】:

    这是可能的解决方案。使用 Xcode 11.4 / iOS 13.4 测试

    class SourceDestinationViewModel: ObservableObject {
        let rate: Double = 2 // just for demo
        
        @Published var source: Double = 0 {
            didSet {
                let newValue = source / rate
                if destination != newValue {
                    destination = newValue
                }
            }
        }
    
        @Published var destination: Double = 0 {
            didSet {
                let newValue = destination * rate
                if source != newValue {
                    source = newValue
                }
            }
        }
    }
    
    struct TestDependentFields: View {
        @ObservedObject var vm = SourceDestinationViewModel()
    
        var body: some View {
            VStack {
                TextField("", text: Binding<String>(get: { String(self.vm.source) },
                    set: { self.vm.source = ($0 as NSString).doubleValue }))
                TextField("", text: Binding<String>(get: { String(self.vm.destination) },
                    set: { self.vm.destination = ($0 as NSString).doubleValue }))
    
                Spacer()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2021-06-06
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多