0
0
iOS Swiftmobile~5 mins

TextField in iOS Swift

Choose your learning style9 modes available
Introduction

A TextField lets users type text into your app. It is like a blank box where you can write words or numbers.

When you want to ask the user for their name.
When you need the user to enter a password.
When you want to search for something by typing keywords.
When you want to collect a phone number or email address.
When you want to let users write comments or messages.
Syntax
iOS Swift
TextField("Placeholder text", text: $variable)
The first part is a placeholder that shows a hint inside the box.
The text: $variable connects the TextField to a variable that stores what the user types.
Examples
This creates a TextField with a hint 'Enter your name' and stores the input in the variable 'name'.
iOS Swift
TextField("Enter your name", text: $name)
This TextField is for email input and shows the email keyboard on the device.
iOS Swift
TextField("Email", text: $email)
  .keyboardType(.emailAddress)
This creates a SecureField for passwords that hides the typed text.
iOS Swift
SecureField("Password", text: $password)
  .textContentType(.password)
Sample App

This app shows a greeting that updates as you type your name in the TextField below.

iOS Swift
import SwiftUI

struct ContentView: View {
  @State private var name = ""

  var body: some View {
    VStack {
      Text("Hello, \(name)!")
        .font(.title)
        .padding()
      TextField("Enter your name", text: $name)
        .textFieldStyle(RoundedBorderTextFieldStyle())
        .padding()
    }
    .padding()
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
OutputSuccess
Important Notes

Use @State to keep track of what the user types in the TextField.

Always add some padding around TextField to make it easier to tap.

Use modifiers like .keyboardType() to show the right keyboard for the input.

Summary

TextField lets users type text into your app.

Connect TextField to a @State variable to store user input.

Use placeholder text to guide users on what to type.