My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

How to create TextField, SecureField, TextEditor and Button in SwiftUI

How to create TextField, SecureField, TextEditor and Button in SwiftUI

rrtutors's photo
rrtutors
·Dec 28, 2021·

2 min read

In SwiftUI, you can use TextField for single line text input andd TextEditor for multiple line text input. As you know for sensitive(secure) information like password, we can still use SwiftUI TextField from UIKit but SwiftUI provided different component as SecureField.

SwiftUI TextField Example

Let's get into each individual component;

TextField:

A control that displays an editable text interface. We can customize the appearance and interaction of TextField by using TextFieldStyle Instance.

TextField is having two parameters:

String which is a placholder for TextField Binding which will capture the text entered by the user

For the Binding object we require to create @State property wrapper to capture the text entered by the user.

SwiftUI uses the @State property wrapper to allow us to modify values inside a struct, which would normally not be allowed because structs are value types.

When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI. This means SwiftUI can destroy and recreate our struct whenever needed (and this can happen a lot!), without losing the state it was storing.

@State should be used with simple struct types such as String, Int, and arrays, and generally shouldn’t be shared with other views. If you want to share values across views, you should probably use @ObservedObject or @EnvironmentObject instead – both of those will ensure that all views will be refreshed when the data changes.

SiwftUI Textfield

TextEditor:

TextEditor is a view in SwiftUI which allows you to display and edit text in your app. The text can consist of multiple lines and can be scrollable.

In order to initialize a TextEditor, you need to pass in a binding to a @State variable which will store the text entered in the TextEditor and also you can format the text like how we did for TextField.

SwiftUI TextEditor SwiftUI TextEditor