如何使用Swift选择UITextField中的所有文本

时间:2015-11-26 04:32:23

标签: swift uitextfield

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

textField.text = "Hello"

textField.becomeFirstResponder()

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

这就是我得到的:

This is what I get:

4 个答案:

答案 0 :(得分:5)

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

首先,在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;
    }
}

答案 1 :(得分:3)

希望这有效。

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

答案 2 :(得分:3)

其他答案都不适合我。事实证明,我需要将代码放在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 :(得分:1)

2017年更新swift 4

#include<iostream>
using namespace std;
class Sample
{
  private:
   const int num;
  public:
   Sample( int i):num(i){}

   int getVal()
    {
     return num;
    }
};
 int main()
  {
   Sample s(12);
   cout<<s.getVal();
  }
相关问题