TextField
Definition​
TextField
is an input field in SwiftUI that accepts text from the user. It requires a binding to a @State
or @Binding
variable to store the entered text.
Basic Syntax​
TextField("Placeholder", text: $text)
Common Modifiers​
TextField("Enter your name", text: $text)
.padding() // Adds internal spacing
.border(Color.gray, width: 1) // Adds border line
.background(Color.white) // Sets background color
.cornerRadius(8) // Rounds the corners
.font(.system(size: 16)) // Sets font and size
.foregroundColor(.black) // Sets text color
.multilineTextAlignment(.leading) // Text alignment: .leading, .center, .trailing
.textFieldStyle(RoundedBorderTextFieldStyle()) // Predefined style
.keyboardType(.default) // Keyboard type: .numberPad, .emailAddress, etc.
.disableAutocorrection(true) // Disables autocorrection
.autocapitalization(.words) // Auto capitalization: .none, .words, .sentences, .allCharacters
.onCommit {
// Code executed when return is pressed
print("User finished editing")
}
.onChange(of: text) { newValue in
// Responds to real-time text changes
print("Text changed to: \(newValue)")
}
TextField Styles​
// Rounded border style
TextField("Name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
// Plain style
TextField("Email", text: $email)
.textFieldStyle(PlainTextFieldStyle())
// Custom style
TextField("Password", text: $password)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(8)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.blue, lineWidth: 1)
)
Keyboard Types​
TextField("Phone", text: $phone)
.keyboardType(.phonePad)
TextField("Email", text: $email)
.keyboardType(.emailAddress)
TextField("Amount", text: $amount)
.keyboardType(.decimalPad)
TextField("Website", text: $url)
.keyboardType(.URL)
Secure Text Input​
SecureField("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle())
Focus Management​
struct ContentView: View {
@State private var username = ""
@State private var password = ""
@FocusState private var isUsernameFocused: Bool
@FocusState private var isPasswordFocused: Bool
var body: some View {
VStack {
TextField("Username", text: $username)
.focused($isUsernameFocused)
.textFieldStyle(RoundedBorderTextFieldStyle())
SecureField("Password", text: $password)
.focused($isPasswordFocused)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Login") {
// Handle login
}
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
isUsernameFocused = false
isPasswordFocused = false
}
}
}
}
}
Validation Example​
struct ValidatedTextField: View {
@State private var email = ""
@State private var isValidEmail = false
var body: some View {
VStack(alignment: .leading) {
TextField("Email Address", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.emailAddress)
.autocapitalization(.none)
.onChange(of: email) { newValue in
isValidEmail = isValidEmailFormat(newValue)
}
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(isValidEmail ? Color.green : Color.red, lineWidth: 1)
)
if !isValidEmail && !email.isEmpty {
Text("Please enter a valid email address")
.foregroundColor(.red)
.font(.caption)
}
}
}
private func isValidEmailFormat(_ email: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailRegex)
return emailPredicate.evaluate(with: email)
}
}
Best Practices​
- Always use bindings: TextField requires a binding to work properly
- Provide clear placeholders: Help users understand what input is expected
- Set appropriate keyboard types: Makes data entry easier for users
- Handle validation: Provide real-time feedback for user input
- Use SecureField for passwords: Never use TextField for sensitive data
- Consider accessibility: Add accessibility labels and hints when needed
Common Use Cases​
- User registration forms
- Search bars
- Data entry screens
- Settings input fields
- Chat message composition