.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)
        }
    }
}

History

  1. 2022.03.31

Last updated