How to select all text in a UITextField using Swift

狂风中的少年 提交于 2019-12-06 22:49:43

问题


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:


回答1:


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;
    }
}



回答2:


Hope this works.

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



回答3:


None of the other answers worked for me. It turned out that I needed to place 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 learned that there are some additional ways to select all text that others may find helpful:

// Select all without showing menu (Cut, Copy, etc)
textField.SelectAll(nil)

// Select all and show menu
textField.SelectAll(self)



回答4:


Update for swift 4 from 2017

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


来源:https://stackoverflow.com/questions/33930656/how-to-select-all-text-in-a-uitextfield-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!