SwiftUI - Focus



Focus is a special feature in SwiftUI, and it identifies which element will receive the next input. Or we can say that focus is used to control and manage which UI component will receive user input or attention.

It creates a seamless user experience, especially while working with forms with multiple buttons or text-fields, keyboard management to control when the keyboard will appear or disappear, accessibility to make sure that the user can navigate the interface properly, etc. It was first introduced in iOS 15 to provide a structured way to manage the focus states of different UI components present in an app.

To use focus in the app, we have to use the pre-defined modifier and property wrapper−

  • @FocusState Property Wrapper

  • focused Modifier

The @FocusState Property Wrapper in SwiftUI

The @FocusState is a powerful property wrapper for tacking which view is receiving focus. It can be a boolean value to control the tracking of a single field or an enum to control the tracking of multiple fields. It is generally used in conjunction with the focused() modifier to describe the location and appearance of the view that gets the current focus. So whenever a view gets focused, the value wrapped inside the @FocusState property will be set to true or given prototype value, whereas when focus leaves the view, it will be set to false.

Syntax

Following is the syntax−

@FocusState private var value: Bool

Example

The following SwiftUI program is used to set focus on a text field.

import SwiftUI

struct ContentView: View {
   @State private var name: String = ""
   
   // Focus state for the given text field
   @FocusState private var isFocused: Bool

   var body: some View {
      VStack{
         TextField("Enter your name", text: $name)
            .padding()
            .background(.teal.opacity(0.4))
            .cornerRadius(8)
         
            // Attaching focus to text field
            .focused($isFocused)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()

         Button("Focus on Field") {
            isFocused = true
         }
         Button("Dismiss Focus") {
            isFocused = false
         }
      }.padding()
   }
}

#Preview {
   ContentView()
}

Output

Focus

Focused Modifier in SwiftUI

The .focused() modifier is used to bind the focus state of the UI components or any other element with the given state value, i.e., @FocusState property. It allows us to control and manage the focus between the given elements. Or we can say this modifier sets the focus on the specified element whenever the value of the @FocusState property is set to true.

Syntax

Following is the syntax−

func focused(_ condition: FocusStateBinding)

Parameter

It takes only one parameter which is the state to which the focus is bound. By default, SwiftUI automatically dismisses focus. When the focus moves to the view, the binding value is set to true, whereas when the focus leaves the view, the binding value is set to false.

Example

The following SwiftUI program is used to adjust focus.

import SwiftUI

struct ContentView: View {
   @State private var name: String = ""
   
   // Focus state for the given text field
   @FocusState private var isFocused: Bool

   var body: some View {
      VStack{
         TextField("Enter your name", text: $name)
            .padding()
            .background(.teal.opacity(0.4))
            .cornerRadius(8)
         
            // Attaching focus to text field
            .focused($isFocused)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()

         Button("Focus on Field") {
            isFocused = true
         }
         Button("Dismiss Focus") {
            isFocused = false
         }
      }
      .padding()
   }
}
#Preview {
   ContentView()
}

Output

Focus

Multiple Focused Elements in SwiftUI

In SwiftUI, we are allowed to set focus on multiple input fields or elements with the help of enum. Here, the focus is adjusted according to the user's actions. It is useful when we are working with a sign-in page, selecting multiple products, or any form that requires multiple input fields.

Example

The following SwiftUI program is used to adjust multiple focuses in the given form.

import SwiftUI

struct ContentView: View {
   @State private var name: String = ""
   @State private var city: String = ""
   @State private var branch: String = ""
   
   // Focus state to manage multiple focus
   @FocusState private var focused: myFields?

   enum myFields {
      case name
      case city
      case branch
   }

   var body: some View {
      VStack{
         TextField("Enter your name", text: $name)
            .focused($focused, equals: .name)
            .padding()
            .background(Color(.systemGray6))
            .cornerRadius(8)

         TextField("Enter you city", text: $city)
            .focused($focused, equals: .city)
            .padding()
            .background(Color(.systemGray6))
            .cornerRadius(8)
         
         TextField("Enter you branch", text: $branch)
            .focused($focused, equals: .branch)
            .padding()
            .background(Color(.systemGray6))
            .cornerRadius(8)

         HStack {
            Button("Move Focus to next") {
               // Move focus to the next field
               switch focused{
               case .name:
                  focused = .city
               case .city:
                  focused = .branch
               case .branch:
                  focused = nil
               default:
                  break
               }
            }.padding()
            .background(.blue)
            .foregroundStyle(.white)
            .cornerRadius(8)
            
            // Submitting form
            Button("Submit") {
               focused = nil
            }
            .padding()
            .background(.yellow)
            .foregroundStyle(.white)
            .cornerRadius(8)
         }
      }
   }
}
#Preview {
   ContentView()
}

Output

Focus
Advertisements