代码之家  ›  专栏  ›  技术社区  ›  ragnarius

为什么这两个皮克的。着火了吗?

  •  0
  • ragnarius  · 技术社区  · 4 年前

    在下面的swiftUI视图中,有两个布尔@State变量( boolA boolB )连接到两个不同的选择器。每个采摘者都有一个 .onReceive ,与以下出版商合作

    [self.boolA].publisher.first()
    

    (老实说,我不明白这一行代码,但它出现在S.O.的几个答案中。)

    无论如何, 无论哪个 我换衣服 二者都开火!

    问题:1)为什么两者都着火了?2) 如何避免这种情况?

    struct ContentView: View {
    @State private var boolA = false
    @State private var boolB = false
    
    var body: some View {
        
        VStack{
            Picker(selection: $boolA, label: Text("a? ")) {
                Text("a is true").tag(true)
                Text("a is false").tag(false)
            }
            .pickerStyle(SegmentedPickerStyle())
            .onReceive([self.boolA].publisher.first()) { _ in
                print("on receive on boolA")
            }
            
            Picker(selection: $boolB, label: Text("b? ")) {
                Text("b is true").tag(true)
                Text("b is false").tag(false)
            }
          .pickerStyle(SegmentedPickerStyle())
            .onReceive([self.boolB].publisher.first()) { _ in
                print("on receive on boolB")
            }
            Spacer()
        }
        
    }
    

    }

    Two pickers

    1 回复  |  直到 4 年前
        1
  •  0
  •   Frankenstein    4 年前

    你只需要一个 onRecieved 在你的 View .以下是代码:

    struct ContentView: View {
        @State private var boolA = false
        @State private var boolB = false
    
        var body: some View {
            VStack{
                Picker(selection: $boolA, label: Text("a? ")) {
                    Text("a is true").tag(true)
                    Text("a is false").tag(false)
                }
                .pickerStyle(SegmentedPickerStyle())
                Picker(selection: $boolB, label: Text("b? ")) {
                    Text("b is true").tag(true)
                    Text("b is false").tag(false)
                }
                .pickerStyle(SegmentedPickerStyle())
                Spacer()
                .onReceive([self.boolA, self.boolB].publisher.first()) { _ in
                    print("boolA:", self.boolA, "boolB:", self.boolB)
                }
            }
        }
    }