Select all text in a UITextField using Swift
In case you need this to work with a SwiftUI TextField, you can use Introspect:
import Introspect
private class TextFieldObserver: NSObject {
@objc
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.selectAll(nil)
}
}
struct ContentView {
private let textFieldObserver = TextFieldObserver()
var body: some View {
TextField(...)
.introspectTextField { textField in
textField.addTarget(
self.textFieldObserver,
action: #selector(TextFieldObserver.textFieldDidBeginEditing),
for: .editingDidBegin
)
}
}
}
Note that you shouldn't override textField.delegate
as SwiftUI sets up its own delegate that is supposed to be hidden from you.
It works in the same way like in Objective-C:
textField.becomeFirstResponder()
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
Try this:
Make sure you conform to the UITextFieldDelegate
and implement:
func textFieldDidBeginEditing(_ textField: UITextField) {
//highlights all text
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}
textField.becomeFirstResponder()
textField.selectAll(nil)