SwiftUI - Text Input and Output



User input and output is the essential concept of a user interface. It is the prime way through which the user interacts with the application. User input is the action taken by the user through which the user provides data to the application.

In contrast, user output is the feedback or information given by the application to the user. SwiftUI handles the text input and output very easily. It required only the three main components to get the user input and output and the components. Let us look at them one by one.

State Management

It is used to store the user input in the view. If any change happens to the state variable it will automatically update user interface.

Syntax

Following is the syntax −

@State private var userData: String = ""

TextField

It allows user to enter data. By default, it does not have any border so in the preview, you would not see anything. You need to tap inside the place where the placeholder text displays to activate the keyboard.

Syntax

Following is the syntax −

TextField("text", text:$bindingVariable)

Parameter

This function takes the following parameters −

  • text: It is the placeholder text that will display when the field is empty.
  • $bindingVariable It connects the text field to the state variable.

Text

It is used to display the entered data.

Syntax

Following is the syntax −

Text("text:\(userData)")

It displays the value of "userData". If the value of userData changes then the displayed text will change automatically.

Note: While working with TextField you would not be able to type in the preview layout. So to enter data you need to build and run your code in the simulator by pressing cmd + R.

Example 1

The following SwiftUI program is used to create a simple text field which takes user input and displays the output.

import SwiftUI

struct ContentView: View {
   @State private var userData: String = ""
   var body: some View {
      VStack{
         TextField("Enter data", text: $userData)
         Text("Entered data: \(userData)")
      }      
   }
}
#Preview {
   ContentView()
}

Output

input Output

Example 2

The following SwiftUI program is used to get data from the user and display the entered data.

import SwiftUI

struct ContentView: View {
   @State private var inputData: String = ""
   var body: some View {
      VStack{            
         // For input
         TextField("Write here...", text: $inputData)
            .padding(10)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .frame(width: 250)
            .font(.largeTitle)
            .background(.mint)
         
         // For output
         Text("Output: \(inputData)").font(.title)
        }
    }
}
#Preview {
    ContentView()
}

Output

input Output
Advertisements