I'm using below code, but for some reason it's not working. Any idea?
textField.text = "Hello"
textField.becomeFirstResponder()
textField.selectedTextRange = self.textField.textRangeFromPosition(self.textField.beginningOfDocument, toPosition: self.textField.endOfDocument)
This is what I get:
Swift's Text views represent static, unselectable text by default, but you can change that using the . textSelection() modifier with the . enabled value.
A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).
I had the same problem and I solved like this:
First, implement UITextFieldDelegate in your ViewController
class ViewController : UITextFieldDelegate
Then, set your textField delegate to "self"
textField.delegate = self
Then, add this function to your ViewController class
func textFieldDidBeginEditing(textField: UITextField) {
textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument)
}
If you are already using the ViewController as delegate for other TextFields that you don't want to behave this way, you can just use a switch, like this:
func textFieldDidBeginEditing(textField: UITextField) {
switch textField {
case yourTextField:
textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument)
break;
case default:
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With