TextField in SwiftUI

Introduction

Pre-requisite for SwiftUI development :-

  1. Xcode 11
  2. MacOS Catalina 10.15.2

Getting Started

A control that displays an editable text interface. In this tutorial You’re learn the following properties of a UITextField.

  1. Basic Text Field
  2. TextField Placeholder Font
  3. TextField Border and Corner Radius
  4. TextField With Icons
  5. Secure TextField

Application Entry Point

Creating a New Project for Playing with SwiftUI. First, fire up Xcode and create a new Project. I created a project named DemoTextField.

Basic Text Field

For your first text field, simple type out the following code:

TextField(" Enter some text", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
@State var name: String = "Rishabh"

Text Field Placeholder Font

You can use the modifier named font and specify your preferred font (e.g. .headline) like this:

TextField("Enter some text", text: $name).textFieldStyle(RoundedBorderTextFieldStyle()).font(.headline)

Text Field Border and Corner Radius

You can use the .overlay, which will add a layer in front of the text field.

TextField("Enter some text", text: $name).padding(10).foregroundColor(.red).overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.red, lineWidth: 2))

Text Field with Icons

You can have images on both sides and remove the default style and configure it with your own style.

HStack {
Image(systemName: “person”).foregroundColor(.gray).padding(30)
TextField(“Enter some text”, text: $name)
}

Secure TextField

SecureField provides a secure text which in most cases is the password. Instead of using TextField, you will use SecureField and it has the same parameter as TextField.

SecureField(“Password”, text: $password)

Conclusion

In this tutorial, we got an introduction about the UITextField control of SwiftUI. This new framework allows developers to easily build flexible UITextField controls with a few lines of code.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rishabh Jain

Rishabh Jain

Sr. iOS Developer | AR | ML | SwiftUI