[英]How to update SwiftUI view after @AppStorage in a separate struct gets updated
我有以下 class:
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)
}
}
我希望在從UserDefaults
更改savedCurrency
后重新呈現視圖。
當@AppStorage
是視圖的一部分時,我讓它很容易工作,但我不確定在這種情況下該怎么做。 我嘗試將@ObservableObject
與@Published
一起使用,或者嘗試創建一個Combine Publisher
並訂閱它,但也沒有成功。
正如@Klaas 所指出的,從 iOS 14.5 開始,可以在ObservableObject
中使用@AppStorage
( 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)
}
}
正如@Asperi @AppStorage
所指出的,應該只在View
中使用。 隱含地也寫在這里: https://developer.apple.com/documentation/swiftui/appstorage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.