swift - 在 SwiftUI 中将可观察对象的通知更改为嵌套对象

标签 swift swiftui

我有以下场景。

我有一个 AppState,它由一个 Foo 类型的对象组成。 Foo 有一个计数器变量,我想在计数器值更新时调用 objectWillChange,这样我就可以更新 UI。

目前没有任何事情发生。增量函数被调用,但 UI 永远不会更新。




import Foundation
import Combine

class Foo: ObservableObject {
    @Published var counter: Int = 999
    
    func increment() {
        counter += 1 // how to get notified when counter value changes
    }
}

class AppState: ObservableObject {
    
    @Published var foo: Foo = Foo()
}

// usage in Scene Delegate as Environment Object
let appState = AppState()

// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIHostingController(rootView: accountSummaryScreen.environmentObject(appState))

更新

class Foo: ObservableObject {
    @Published var counter: Int = 999 {
        didSet {
            objectWillChange.send() 
        }
    }
    
    func increment() {
        counter += 1 // how to get notified when counter value changes
    }
}

最佳答案

未检测到更改,因为作为引用类型的 Foo 实际上并没有更改 - 它是相同的引用,所以 @Published 在这里没有帮助.

AppState 需要手动订阅更改并调用它自己的 objectWillChange.send:

class AppState: ObservableObject {
    
    var foo: Foo = Foo() {
       didSet {
          cancellables = []
          foo.$counter
             .map { _ in } // ignore actual values
             .sink(receiveValue: self.objectWillChange.send)
             .store(in: &cancellables)
       }
    }

    private var cancellables: Set<AnyCancellable> = []
}

关于swift - 在 SwiftUI 中将可观察对象的通知更改为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63251715/

相关文章:

swift - 是否有 Swift 单行代码从数组中删除元素(如果存在)并在不存在时附加它?

ios - XCode 6 无法识别第二个 tableViewCell

ios - 调整 webView 大小时如何修复 webView 的粗糙滚动行为?

ios - Swift UI 相机显示纵向 View ,但图像变成横向 View

使用 SwiftUI 运行 Xcode 11 时出现 Swift 编译器问题

ios - PHPickerViewController 点击搜索得到错误... "Unable to load photos"

swift - 如何将 NSTextFields 添加到 NSScrollView

ios - 隐藏和显示音量指示器

ios - SwiftUI - 单击按钮打开新 View

SwiftUI NavigationLink 隐藏箭头