我有以下课程:
struct PriceFormatter {
@AppStorage(UserDefaultsKey.savedCurrency)
var savedCurrency: String?
let price: Float
init(price: Float) {
self.price = price
}
var formatted: String {
return "\(savedCurrency) \(price)"
}
}
以及以下视图:
struct PriceText: View {
let price: Float
var body: some View {
Text(PriceFormatter(price: self.price).formatted)
}
}
我希望视图在之后重新渲染savedCurrency
from UserDefaults
变化。
我让它很容易工作,当@AppStorage
是视图的一部分,但我不确定在这种情况下该怎么做。我尝试使用@ObservableObject
with @Published
或尝试进行组合Publisher
并订阅它,但也没有成功。
UPDATE
正如 @Klaas 所指出的,从 iOS 14.5 开始,人们可以使用@AppStorage
在 - 的里面ObservableObject
(https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-14_5-release-notes https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-14_5-release-notes)
工作解决方案现在看起来像这样:
class PriceFormatter: ObservableObject {
@AppStorage(UserDefaultsKey.savedCurrency)
var savedCurrency: String?
let price: Float
init(price: Float) {
self.price = price
}
var formatted: String {
return "\(savedCurrency) \(price)"
}
}
并像这样使用:
struct PriceText: View {
@StateObject var formatter = PriceFormatter(price: 5)
var body: some View {
Text(formatter.formatted)
}
}
老答案。适用于 iOS
正如@Asperi 所指出的@AppStorage
应该只用于View
。这里也隐含地写着:https://developer.apple.com/documentation/swiftui/appstorage https://developer.apple.com/documentation/swiftui/appstorage
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)