Skip to content
DeveloperMemos

How to Use the Focused Modifier in SwiftUI

SwiftUI, Focused Modifier1 min read

In SwiftUI, the Focused modifier is used to manage the focus state of a view. This modifier is used to indicate whether a view is currently focused or not. In this post, we will learn how to use the Focused modifier in SwiftUI with some code examples.

What is the Focused Modifier?

The Focused modifier is a property wrapper that is used to manage the focus state of a view. This modifier is used to indicate whether a view is currently focused or not. When a view is focused, it means that the user is currently interacting with that view. The Focused modifier is used to manage the focus state of a view in SwiftUI.

How to Use the Focused Modifier?

To use the Focused modifier in SwiftUI, you need to follow these steps:

  1. Import the FocusState and Focused modifiers:
1import SwiftUI
2
3@available(iOS 15.0, *)
4struct ContentView: View {
5 @FocusState private var isFocused: Bool
6 @State private var text: String = ""
7
8 var body: some View {
9 TextField("Enter text", text: $text)
10 .focused($isFocused)
11 }
12}
  1. Create a @FocusState property to manage the focus state of the view:
1@FocusState private var isFocused: Bool
  1. Use the focused modifier to bind the focus state of the view to the @FocusState property:
1.focused($isFocused)
  1. Use the isFocused property to check whether the view is currently focused or not:
1if isFocused {
2 // Do something when the view is focused
3} else {
4 // Do something when the view is not focused
5}

Example

Here's an example of how to use the Focused modifier in SwiftUI:

1import SwiftUI
2
3@available(iOS 15.0, *)
4struct ContentView: View {
5 @FocusState private var isFocused: Bool
6 @State private var text: String = ""
7
8 var body: some View {
9 VStack {
10 TextField("Enter text", text: $text)
11 .focused($isFocused)
12
13 if isFocused {
14 Text("The text field is currently focused.")
15 } else {
16 Text("The text field is not currently focused.")
17 }
18 }
19 }
20}

In this example, we have a TextField that is bound to the isFocused property using the focused modifier. We also have a Text view that displays a message depending on whether the TextField is currently focused or not.

Wrap Up

In this post, we learned how to use the Focused modifier in SwiftUI to manage the focus state of a view. We also saw an example of how to use the Focused modifier in SwiftUI. The Focused modifier is a powerful tool that can be used to create more interactive and engaging user interfaces in SwiftUI.