โจ.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)
}
}
}
Foundation โฉ
Data Formatting โฉ
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
Was this helpful?