TextField
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 24 of 50.
A TextField lets the user type. It needs a placeholder and a binding to a String state:
@State private var name = ""
var body: some View {
VStack {
TextField("Your name", text: $name)
Text("Hello, \(name)!")
}
}The $ in $name turns the state into a binding: a two-way connection. The field shows the value of name, and every key the user types writes back into it. The text below reads the same state, so it updates on each keystroke.
.textFieldStyle(.roundedBorder) draws the familiar rounded box around the field.
Challenge
EasyGreet the user by name. Add a TextField with the placeholder Your name bound to name, and give it the identifier name. Keep the greeting text, which should read Hello, Ada! after the user types Ada.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground