【问题标题】:swiftui cannot change @State value in sinkswiftui 无法更改接收器中的@State 值
【发布时间】:2021-07-14 17:14:49
【问题描述】:

我现在正在学习 swiftui,我是 stackoverflow 的新手,我发现一个问题,这是我的代码。我想更改 sink 中的@State nopubName,但它不起作用,打印总是“Nimar”,我不知道为什么

struct ContentView: View {
   
    @State var nopubName: String = "Nimar"
    private var cancellable: AnyCancellable?
    
    var stringSubject = PassthroughSubject<String, Never>()

    init() {
        cancellable = stringSubject.sink(receiveValue: handleValue(_:))
    }
    
    func handleValue(_ value: String) {
         print("handleValue: '\(value)'")
        self.nopubName = value
        print("in sink "+nopubName)
     }
    
    var body: some View {
        VStack {
            Text(self.nopubName)
                .font(.title).bold()
                .foregroundColor(.red)
            Spacer()
 
            Button("sink"){
                stringSubject.send("World")
                print(nopubName)

            }
        }
    }
}

【问题讨论】:

    标签: state combine sink


    【解决方案1】:

    您应该只从视图主体内部或通过它调用的方法访问状态属性。

    https://developer.apple.com/documentation/swiftui/state

    您可以在 ObservableObject 中使用该功能并更新 @Published 以保持 UI 更新

    https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

    【讨论】:

      【解决方案2】:

      你不需要使用Combine,如果你在View之内,你可以直接改变@State变量的值

      struct ContentView: View {
          @State var nopubName: String = "Nimar"
          var body: some View {
              VStack {
                  Text(self.nopubName)
                      .font(.title).bold()
                      .foregroundColor(.red)
                  Spacer()
      
                  Button("sink"){
                      nopubName = "World"
                  }
              }
          }
      }
      

      【讨论】:

      • 感谢您的回复。是的,我知道,但我想学习另一种更新视图的方法,但它似乎不起作用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多