gpt4 book ai didi

swiftui - iOS 13.4 : didSet() not called anymore for a @Published Bool when using toggle()

转载 作者:行者123 更新时间:2023-12-02 11:18:20 30 4
gpt4 key购买 nike

在 iOS 13.4 之前,我使用属性观察器更新 @Published Bool 值的 UserDefaults

@Published var mutedAudio: Bool = UserDefaults.standard.bool(forKey: "mutedAudio") {  
didSet { UserDefaults.standard.set(self.mutedAudio, forKey: "mutedAudio") }
}

在 iOS 13.4 的第一个测试版中,如果我在 SwiftUI 中使用 toggle() 方法,则不再调用 didSet(),并且我必须使用逻辑否定:
Button(action: {  
// self.settings.mutedAudio.toggle() doesn't work in iOS 13.4
self.settings.mutedAudio = !self.settings.mutedAudio // workaround
}) {
Image(systemName: settings.mutedAudio ? "speaker.slash.fill" : "speaker.2.fill").resizable().frame(width: 24, height: 24)
}

还有比等待下一个 iOS 13.4 测试版更好的解决方案吗?

最佳答案

你可以直接在你的 init 或其他地方订阅 mutedAudio,例如:

class SomeClass: ObservableObject {
var cancellable: Cancellable?

@Published var mutedAudio: Bool = UserDefaults.standard.bool(forKey: "mutedAudio")

init() {
cancelable = $mutedAudio.sink(receiveValue: { (value) in
UserDefaults.standard.set(value, forKey: "mutedAudio")
})
}
}

关于swiftui - iOS 13.4 : didSet() not called anymore for a @Published Bool when using toggle(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60130373/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com