我試圖用它@AppStorage來讀取/保存一個值并用它計算一些東西,但是我沒有在我的ContentView. 例子:
助手.swift
func powerized(x: Decimal) -> Decimal {
let powerized: Decimal = pow(x, 3) * 6.25
return powerized
}
內容視圖.swift
import SwiftUI
struct ContentView: View {
@AppStorage(StorageKeys.sourcePower.rawValue) var sourcePower = 15
var body: some View {
VStack {
Text(powerized(x: sourcePower))
}
}
}
通過這個實作,我得到Initializer 'init(_:)' requires that 'Decimal' conform to 'StringProtocol'.
如果我放一個
var myValue: Decimal = powerized(x: sourcePower)
Text(myValue)
我收到轉換錯誤Cannot convert value of type 'Int' to expected argument type 'Decimal'。這可能是因為變數未定義為,Decimal但即使進行了更改,我也得到了
Cannot use instance member 'age' within property initializer; property initializers run before 'self' is available.
我對此感到非常生氣。是否有任何更改使其在不創建新類的情況下作業ObservableObject?AppStorage已經解決了每次更改 UI 時都更新它的問題。我認為,作為一種解決方法,理論上我可以使用我的函式預先計算我想要的內容,并將其存盤以及源值,但這沒有任何意義。
uj5u.com熱心網友回復:
它與 . 無關@AppStorage。您的powerized函式回傳一個小數,并且您嘗試使用 is in a Text()。Text()需要一個String. 你可以做:
var body: some View {
VStack {
// Use .description which returns a String
Text(powerized(x: sourcePower).description)
}
}
其中任何一個都將使其成為String.
uj5u.com熱心網友回復:
由于小數在不同國家/地區的格式不同(例如,有些使用逗號作為小數點),因此您必須使用格式化程式,并且為此提供了一個新的便利 API:
Text(powerized(x: sourcePower), format: .number)
這樣,如果區域設定更改,標簽也會自動更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452653.html
