TextField
- Text fields in SwiftUI can be formatted using the
.currency format, with the currency code determined dynamically using Locale.current.currencyCode.
- The
.keyboardType modifier allows customization of the keyboard type for text fields.
- Choosing
.numberPad or .decimalPad keyboard types restricts input to numeric values.
- The
@FocusState property wrapper is used to handle input focus in SwiftUI.
- The
.focused modifier is applied to the text field to bind it.
Sample code
- The
checkAmount property is marked with @State to enable automatic UI updates.
- The
TextField is configured to display the checkAmount value as a currency using the .currency format.
- The
Locale.current.currencyCode is used to dynamically determine the currency code.
- The
.keyboardType(.decimalPad) modifier restricts input to numeric values with a decimal point.
@State private var checkAmount = 0.0
var body: some View {
Form {
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
}
}
}
- The
@FocusState property amountIsFocused is added to track the focus of the text field.
- The
.focused modifier is applied to the text field, binding it to the amountIsFocused property.
@FocusState private var amountIsFocused: Bool
// ...
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
Picker
- Pickers in SwiftUI require a two-way binding to a property to track and update their value.
- The
ForEach view can be used to loop over a range of numbers and display them in the picker.