SwiftUI – How to create and style a Text Field

Share on facebook
Share on twitter
Share on pinterest

Wanna know how to create and customize a Text Field in SwiftUI? Here you go! 👇

Step 1: Create a State property that holds the user’s input. For more on how State properties work and how they are used with Text fields check out our login page tutorial!

Step 2: Initialize the TextField object. Enter a string which serves as the placeholder when the TextField is empty. Next, you need to bind the created State propery to the TextField to enable data flow between them. To understand the data flow concept in SwiftUI we recommend you our login page tutorial as well.

Step 3: In SwiftUI, we style the Text Field by adding modifiers to it. For example you can add a rounded background and paddings to the TextField

import SwiftUI

let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)

struct ContentView : View {
    //Create a State property that holds the user's input
    @State var userInput = ""

    var body: some View {
        //Initialize the Text Field, provide it with a placeholder title and bind it to the State
        TextField("Enter something...", text: $userInput)
            //Style your Text Field
            .padding()
            .background(lightGreyColor)
            .cornerRadius(5.0)
            .padding()
    }
}

And that’s everything you need to know to use a Text Field for your SwiftUI app.


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount

small_c_popup.png

Are you ready for a new era of iOS development?

Start learning swiftUI today - download our free e-book