✨.currency
📗 參考:Paul ⟩ Reading text from the user with TextField
struct WeSplitApp: View {
@State private var checkAmount = 0.0 // Double
var body: some View {
// ⭐️ 當地貨幣碼:Locale.current.currencyCode
let code = Locale.current.currencyCode ?? "USD" // TWD
// ⭐️ FloatingPointFormatStyle<Value>.Currency
let currency: FloatingPointFormatStyle<Double>.Currency =
.currency(code: code)
NavigationView {
Form {
Section {
TextField(
"Amount",
value: $checkAmount,
format: currency // ⭐️ 數字格式:貨幣
)
// ---------------------------------------------------
// ❗️ this won't stop users from entering other values
// if they have a hardware keyboard or
// if they copy/paste text from elsewhere.
// ---------------------------------------------------
.keyboardType(.decimalPad) // ⭐️ 數字鍵盤
}
Section {
Text(checkAmount, format: currency)// ⭐️ 數字格式:貨幣
}
}
.navigationTitle("We Split")
.navigationBarTitleDisplayMode(.inline)
}
}
}
Locale (struct)
FormatStyle (protocol) ⭐️
ParseableFormatStyle (protocol)
FloatingPointFormatStyle<Value> (generic struct) ⭐️
FloatingPointFormatStyle.Currency
.currency<Value>(code:) where Value : BinaryFloatingPoint
SwiftUI ⟩ Text Input and Output ⟩ TextField ⟩
.init(_:value:format:prompt:) ⭐️ create a text field that binds to a bound value, using a
ParseableFormatStyle
to convert to and from this type.
History
2022.03.31
struct WeSplitApp: View {
@State private var checkAmount = 0.0
@State private var numberOfPeople = 2
@State private var tipPercentage = 20
let tipPercentages = [10, 15, 20, 25, 0]
var body: some View {
NavigationView {
Form {
Section {
// ⭐️ TextField with format
TextField(
"Amount",
value: $checkAmount,
format: .currency(code: Locale.current.currencyCode ?? "USD")
)
// ---------------------------------------------------
// ❗️ this won't stop users from entering other values
// if they have a hardware keyboard or
// if they copy/paste text from elsewhere.
// ---------------------------------------------------
.keyboardType(.decimalPad)
}
Section {
Text(checkAmount, format: .currency(code: Locale.current.currencyCode ?? "TWD"))
}
}
.navigationTitle("We Split")
.navigationBarTitleDisplayMode(.inline)
}
}
Last updated