For automatic call of focus:
Use ViewModifier
for custom case iOS 14/15+ in work with FocusState
on iOS 15+.
In iOS 14 focused don't work with FocusState
.
import SwiftUI
@available(iOS 15.0, *)
private struct TextFieldFocused: ViewModifier {
@FocusState private var focused: Bool
init() {
self.focused = false
}
func body(content: Content) -> some View {
content
.focused($focused)
.onAppear {
focused = true
}
}
}
extension View {
@ViewBuilder
func focused() -> some View {
if #available(iOS 15.0, *) {
self.modifier(TextFieldFocused())
} else {
self
}
}
}
In your view any text fields:
TextField("Enter text", text: .constant(""))
.focused()
For manually call of focus:
import SwiftUI
@available(iOS 15.0, *)
private struct TextFieldFocused: ViewModifier {
@FocusState private var focused: Bool
@Binding private var externalFocused: Bool
init(externalFocused: Binding<Bool>) {
self._externalFocused = externalFocused
self.focused = externalFocused.wrappedValue
}
func body(content: Content) -> some View {
content
.focused($focused)
.onChange(of: externalFocused) { newValue in
focused = newValue
}
.onChange(of: focused) { newValue in
externalFocused = newValue
}
.onAppear {
if externalFocused {
focused = true
}
}
}
}
extension View {
@ViewBuilder
func focused(_ value: Binding<Bool>) -> some View {
if #available(iOS 15.0, *) {
self.modifier(TextFieldFocused(externalFocused: value))
} else {
self
}
}
}
In your view:
@State var isFocused: Bool = false
var body: some View {
TextField("Enter text", text: .constant(""))
.focused($isFocused)
}