在UIAlertController的文本字段中select文本

我需要在UIAlertController出现后立即select文本字段的文本。 但是,我在标准UITextField中select文本的方式在这里不起作用。

这是我的尝试,但我似乎无法得到它的工作。

let ac = UIAlertController(title: "Rename", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler({ [] (textField: UITextField) in textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) textField.text = "filename.dat" }) ac.addAction(UIAlertAction(title: "CANCEL", style: .Cancel, handler: nil)) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [] Void in // do something })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(ac, animated: true, completion: nil) }) 

有任何想法吗?

我已经重写了你的代码。 你的类应该符合UITextFieldDelegate协议并实现textFieldDidBeginEditing方法,如下所示:

 class ViewController: UIViewController, UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() let ac = UIAlertController(title: "Rename", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler({ [] (textField: UITextField) in textField.text = "filename.dat" textField.delegate = self }) ac.addAction(UIAlertAction(title: "CANCEL", style: .Cancel, handler: nil)) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [] Void in // do something })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(ac, animated: true, completion: nil) }) } func textFieldDidBeginEditing(textField: UITextField) { textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) textField.becomeFirstResponder() } } 

谢谢,@ridvankucuk。 你的解决scheme很好。

但是textfield委托function可以简化一点:

 func textFieldDidBeginEditing(_ textField: UITextField) { textField.selectAll(nil) } 

select所有文本而不添加委托的方法:

 present(vc, animated: true) { vc.textFields![0].selectAll(nil) }