Description
I want all text in a textfield to be selected when it receives the focus so that the user can just start typing the new data he wants to enter, instead of having to hit backspace until all existing data (if present) is deleted.
When a user enters data in the two textfields in the code below, and then decides he wants to change the data entered in the first textfield, he taps it and has to delete the values manually. How can I make all the text of a textfield selected upon receiving the focus?
import SwiftUI
struct ContentView: View {
@State private var data: String = ""
@State private var data2: String = ""
var body: some View {
VStack {
TextField("Enter data", text: $data)
TextField("Enter data 2", text: $data2)
}
}
}
What I have tried
I tried to write a function that is called by the TextField's parameter onEditingChanged
, but I cannot pass an argument with it.
The textfield then becomes:
TextField("Enter data", text: $data, onEditingChanged: getFocus)
With the function:
func getFocus(bool: Bool) {
if bool == true {
// textfield.selectAll(nil)
}
}