Sélectionnez du text dans le champ de text de UIAlertController

J'ai besoin que le text du champ de text soit sélectionné juste après la présentation du UIAlertController. Cependant, la façon dont je sélectionne le text dans un UITextField standard ne fonctionne pas ici.

C'est ce que j'ai essayé, mais je n'arrive pas à le faire fonctionner.

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

Des idées?

J'ai réécrit ton code. Votre class doit se conformer au protocole UITextFieldDelegate et implémenter la méthode textFieldDidBeginEditing , comme ceci:

 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() } } 

Merci, @ridvankucuk. Votre solution fonctionne très bien.

Mais la fonction de délégué de champ de text peut être simplifiée petit peu:

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