SwiftUI 更新@State关闭

SwiftUI Update @State in closure

提问人:H1Gdev 提问时间:9/30/2022 更新时间:9/30/2022 访问量:350

问:

下面是有问题的 SwiftUI 代码。

struct ContentView : View {
    @State var connection = false

    let disconnectListener: DisconnectListener = {
        class Anonymous: NSObject, DisconnectListener {
            func onDisconnect() {
                // connection variable is invisible and cannot update this ... 
                connection = false
            }
        }
        return Anonymous()
    }()

    var body: some View {
        Toggle(isOn: $connection) {
            Text("Connection").frame(maxWidth: .infinity, alignment: .trailing)
        }.onChange(of: connection) { _ in
            if connection {
                // Listener provided by @protocol in Objective-C.
                controller.add(disconnectListener)
            }
        }
    }
}

我需要这样做并将其添加到.anonymous classcontroller

有没有办法从方法更新变量?@StateconnectiononDisconnect()

Swift Objective-C SwiftUI 闭包

评论


答:

1赞 Dávid Pásztor 9/30/2022 #1

你应该把你的班级移到你的班级之外,并储存在上面。AnonymousViewconnection

class Anonymous: NSObject, DisconnectListener, ObservableObject {
  @Published var connection: Bool

  init(connection: Bool) {
    self.connection = connection
  }

  func onDisconnect() {
    // connection variable is invisible and cannot update this ...
    connection = false
  }
}

struct ConnectionView : View {
  @ObservedObject var disconnectListener: Anonymous

  var body: some View {
    Toggle(isOn: $disconnectListener.connection) {
      Text("Connection").frame(maxWidth: .infinity, alignment: .trailing)
    }.onChange(of: disconnectListener.connection) { connection in
      if connection {
        // Listener provided by @protocol in Objective-C.
        controller.add(disconnectListener)
      }
    }
  }
}

您现在需要注入AnonymousConnectionView

let connectionView = ConnectionView(disconnectListener: Anonymous(connection: false))