Introduction
In a brief introduction, I gave you an overview of SwiftUI and how to build a simple user interface. The SwiftUI framework provides developers with a new way to develop a clean UI, allowing you to make it the same UI with much less code.
In my previous article, you learned how to make table view list and Navigation,
Designing the Text Field and Label
We will begin implementing text fields and labels placing them just above each text field. For creating a label, we simply use a text component and write the code like below.
- Text("NAME").font(.headline)
To create a text field with a placeholder, you can write the code like below.
- TextField("Enter Restaurant NAME", text: $text)
- struct ContentView : View {
- var body: some View {
- VStack(alignment: .leading, spacing: 10.0) {
- Text("NAME").font(.headline)
- TextField("Enter Restaurant NAME", text: $text)
- .padding(.all)
- .clipShape(RoundedRectangle(cornerRadius: 5.0))
- .background(Color(red: 239.0/255.0, green: 243.0/255, blue: 244.0/255.0, opacity:1.0))
- }.padding(.horizontal,15)
- }
- }

For reuse purpose, we will create a separate struct class, which accepts two parameters, label and placeholder -
- struct TextFieldWithLabel: View {
- var label: String
- var placeholder : String
- @State var text: String = ""
- var body: some View {
- VStack(alignment: .leading, spacing: 10.0) {
- Text(label).font(.headline)
- TextField(placeholder, text: $text)
- .padding(.all)
- .clipShape(RoundedRectangle(cornerRadius: 5.0))
- .background(Color(red: 239.0/255.0, green: 243.0/255, blue: 244.0/255.0, opacity:1.0))
- }.padding(.horizontal,15)
- }
- }
Now, you can create a text field by constructing a TextFieldWithLabel struct class with specified Text Label variable. The name is "label" and the text field placeholder variable is "placeholder" like below,
- struct ContentView: View {
- var body: some View {
- TextFieldWithLabel(label:"NAME", placeholder:"Enter Restaurant NAME")
- }
- }
Creating Multiple TextFields using List
To present multiple text fields in a vertical arrangement, you can use "VStack" component to layout the text fields and label. We will make the form scrollable by embedding into a stack using the "List" that allows developers to easily make a table list. Now contentView looks like -


Join the conversation! Your thoughts help the community grow.