SwiftUI TextField: a closer look

DevTechie
DevTechie
Published in
16 min readDec 5, 2021

--

Photo by Glenn Carstens-Peters on Unsplash

TextField is a control that displays an editable text interface. TextField creates an input field that users can interact with. TextField provides the ability to read and write text for apps. UITextField is its counterpart in UIKit.

TextField uses bindable values to get and set text which enables us to work directly with data. Change in data is observed by binding variables and TextField can react to those changes.

Let’s start with a simple TextField example. Simplest form of TextField can be created with a label and a binding value.

Note: If the binding value is of type String then TextField updates the value as user types in the field; otherwise updates to the value happen when the user commits the change by pressing return key.

For this example, we will create a view to add a new DevTechie course. View will have a TextField which will allow users to enter the course’s title. We will create a @State variable named “title” and use it as binding property for TextField.

Reading TextField value is as easy as writing it. We will create a Text view and use it to display title value being typed by the user in TextField.

struct TextFieldExample: View {

@State private var title: String = ""

var body: some View {
VStack {…

--

--