【问题标题】:How to select all text in a UITextField using Swift如何使用 Swift 选择 UITextField 中的所有文本
【发布时间】:2022-03-16 08:28:20
【问题描述】:

我正在使用下面的代码,但由于某种原因它不起作用。有什么想法吗?

textField.text = "Hello"

textField.becomeFirstResponder()

textField.selectedTextRange = self.textField.textRangeFromPosition(self.textField.beginningOfDocument, toPosition: self.textField.endOfDocument)

这是我得到的:

【问题讨论】:

  • “textField”和“self.textField”有什么不同吗?

标签: swift uitextfield


【解决方案1】:

我遇到了同样的问题,我是这样解决的:

首先,在你的 ViewController 中实现 UITextFieldDelegate

class ViewController :  UITextFieldDelegate

然后,将您的 textField 委托设置为“self”

textField.delegate = self

然后,将此函数添加到您的 ViewController 类中

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

如果您已经在使用 ViewController 作为其他 TextField 的委托,而您不想以这种方式运行,则可以只使用一个开关,如下所示:

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

         case default:
              break;
    }
}

【讨论】:

    【解决方案2】:

    其他答案都不适合我。原来我需要把我的代码放在viewDidAppear而不是viewDidLoad

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

    还有一些其他方法可以选择其他人可能认为有帮助的所有文本:

    // Select all without showing menu (Cut, Copy, etc)
    textField.selectAll(nil)
    
    // Select all and show menu
    textField.selectAll(self)
    

    【讨论】:

      【解决方案3】:

      2017 年 Swift 4 的更新

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

      【讨论】:

        【解决方案4】:

        希望这行得通。

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

        【讨论】:

          【解决方案5】:

          我的答案是

          你好,我用这个做

          
            override func selectAll(_ sender: Any?) {
            textView.selectAll(sender)
            }
          

          【讨论】:

          • 这在Anton's answer中已经提到。 在回答已有答案的旧问题时,请确保提供新颖的解决方案或比现有答案更好的解释。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-13
          • 1970-01-01
          • 2017-12-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多