Привязка TextField к состоянию
Подключите текстовое поле к строке @State.
«Привязка TextField к состоянию» — бесплатный урок SwiftUI Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения SwiftUI Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс SwiftUI Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Meet TextField
A TextField is SwiftUI's box where users type. Give it a prompt and somewhere to store what they enter, and you have live text input. ✍️
Text Needs a Home
Typed characters must go somewhere. You store them in a @State string that the text field reads from and writes to as the user types.
@State private var name = ""The Binding Connection
A TextField needs a two-way link called a binding. It both reads the current value and writes new keystrokes back into your state.
The Dollar Sign
To pass a binding, prefix the property with $. Writing $name hands the text field a two-way connection instead of a plain copy.
TextField("Name", text: $name)The Placeholder
The first argument is the placeholder: faint hint text shown when the field is empty. It disappears the moment the user starts typing.
TextField("Enter your name", text: $name)Reading the Value
Because the field writes into your state, you can read name anywhere in the body to react to what the user has typed so far.
Text("Hello, \(name)")A Bordered Look
Add the textFieldStyle modifier with .roundedBorder to give the field a clean, tappable outline instead of a bare line.
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)Live Updates Are Free
You never write code to refresh the screen. When the binding changes the state, SwiftUI re-renders the view automatically for you. ✨
One Source of Truth
The @State string is the single source of truth. The field and any Text that reads it always stay perfectly in sync.
Plain Value vs Binding
Writing name passes a read-only copy. Writing $name passes the binding the field needs to send edits back. The dollar sign matters.
Putting It Together
A state string, a TextField bound with $, and a Text that reads it: that is a complete, reactive input screen.
TextField("Name", text: $name)
Text("Hi, \(name)")Quick Check
How do you give a TextField a two-way link to a @State string?
Recap
You bound a TextField to @State with the $ prefix, so typing updates your value and the UI refreshes itself. That is reactive input in a nutshell. 🎉
Часто задаваемые вопросы
Урок «Привязка TextField к состоянию» бесплатный?
Да — полный текст урока «Привязка TextField к состоянию» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс SwiftUI Academy, подпишись на CoddyKit PRO. Курс SwiftUI Academy содержит 4 уроков всего.
Чему я научусь в уроке «Привязка TextField к состоянию»?
Подключите текстовое поле к строке @State. Ты практикуешь SwiftUI Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать SwiftUI Academy?
Предыдущий опыт не требуется. SwiftUI Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Привязка TextField к состоянию»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке SwiftUI Academy?
Да. Каждый урок SwiftUI Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Привязка TextField к состоянию
- Типы клавиатуры и заполнители
- SecureField для паролей
- Проверка ввода в реальном времени