— SwiftUI, Focused Modifier — 1 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.
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.
To use the Focused
modifier in SwiftUI, you need to follow these steps:
FocusState
and Focused
modifiers:1import SwiftUI2
3@available(iOS 15.0, *)4struct ContentView: View {5 @FocusState private var isFocused: Bool6 @State private var text: String = ""7
8 var body: some View {9 TextField("Enter text", text: $text)10 .focused($isFocused)11 }12}
@FocusState
property to manage the focus state of the view:1@FocusState private var isFocused: Bool
focused
modifier to bind the focus state of the view to the @FocusState
property:1.focused($isFocused)
isFocused
property to check whether the view is currently focused or not:1if isFocused {2 // Do something when the view is focused3} else {4 // Do something when the view is not focused5}
Here's an example of how to use the Focused
modifier in SwiftUI:
1import SwiftUI2
3@available(iOS 15.0, *)4struct ContentView: View {5 @FocusState private var isFocused: Bool6 @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.
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.