Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in a UITextField using Swift

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:

This is what I get:

like image 223
Eduardo Avatar asked Nov 26 '15 04:11

Eduardo


People also ask

How do you select text in Swift?

Swift's Text views represent static, unselectable text by default, but you can change that using the . textSelection() modifier with the . enabled value.

What is TextField in Swift?

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).


1 Answers

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;
    }
}
like image 109
Cauê Jannini Avatar answered Oct 14 '22 14:10

Cauê Jannini