I had issues when using code from some of the answers previously posted here, so I'm just sharing what worked for me.
First of all, you will have to import Combine
:
import Combine
Then you can add this to your TextField
:
.onReceive(NotificationCenter.default.publisher(
for: UITextField.textDidBeginEditingNotification)) { _ in
DispatchQueue.main.async {
UIApplication.shared.sendAction(
#selector(UIResponder.selectAll(_:)), to: nil, from: nil, for: nil
)
}
}
Alternatively, you could use a ViewModifier
for a more reusable approach:
public struct SelectAllTextOnBeginEditingModifier: ViewModifier {
public func body(content: Content) -> some View {
content
.onReceive(NotificationCenter.default.publisher(
for: UITextField.textDidBeginEditingNotification)) { _ in
DispatchQueue.main.async {
UIApplication.shared.sendAction(
#selector(UIResponder.selectAll(_:)), to: nil, from: nil, for: nil
)
}
}
}
}
extension View {
public func selectAllTextOnBeginEditing() -> some View {
modifier(SelectAllTextOnBeginEditingModifier())
}
}
And then just add this to your TextField
:
.selectAllTextOnBeginEditing()