簡體   English   中英

更新單獨結構中的@AppStorage 后如何更新 SwiftUI 視圖

[英]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中使用@AppStoragehttps://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 < 14.5

正如@Asperi @AppStorage所指出的,應該只在View中使用。 隱含地也寫在這里: https://developer.apple.com/documentation/swiftui/appstorage

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM