How to select all text in a UITextField using Swift

I am using the code below, but for some reason it does not work. 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:

+5
source share
4 answers

I had the same problem and solved it like this:

First, implement the UITextFieldDelegate in your ViewController

 class ViewController : UITextFieldDelegate 

Then set the textField delegate to "self"

 textField.delegate = self 

Then add this function to the ViewController class

 func textFieldDidBeginEditing(textField: UITextField) { textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) } 

If you are already using ViewController as a delegate for other text fields that you do not want to behave in this way, you can simply use a switch, for example:

 func textFieldDidBeginEditing(textField: UITextField) { switch textField { case yourTextField: textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) break; case default: break; } } 
+3
source

Hope this works.

  func textFieldDidBeginEditing(textField: UITextField) { textField.selectedTextRange = self.textField.textRangeFromPosition(self.textField.beginningOfDocument, toPosition: self.textField.endOfDocument) } 
+2
source

None of the other answers worked for me. It turned out that I needed to put my code in viewDidAppear instead of viewDidLoad :

 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textField.becomeFirstResponder() textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) } 

I also found out that there are some additional ways to select all the text that others might find useful:

 // Select all without showing menu (Cut, Copy, etc) textField.SelectAll(nil) // Select all and show menu textField.SelectAll(self) 
+2
source

Update for Quick 4 from 2017

  func textFieldDidBeginEditing(_ textField: UITextField) { textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) } 
0
source

Source: https://habr.com/ru/post/1236874/


All Articles