TextField in SwiftUI
Create a Simple TextField in SwiftUI
Introduction
Pre-requisite for SwiftUI development :-
- Xcode 11
- 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.
- Basic Text Field
- TextField Placeholder Font
- TextField Border and Corner Radius
- TextField With Icons
- 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.
Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas.
By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn’t render the app preview. You have to click the Resume button in order to see the preview.
Basic Text Field
For your first text field, simple type out the following code:
TextField(" Enter some text", text: $name).textFieldStyle(RoundedBorderTextFieldStyle())
Remember to create a variable to bind your text field with the following code. Now you can access the output by simply using the variable provided below.
@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.
Thanks for reading and good luck with your next SwiftUI Tutorial!