Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text in UIAlertController's text field

I need the text of the text field to be selected right after the UIAlertController is presented. However, the way I select text in a standard UITextField doesn't work here.

This is what I tried, but I can't seem to get it work.

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

Any ideas?

like image 572
Antonin Charvat Avatar asked Mar 14 '16 15:03

Antonin Charvat


3 Answers

I have rewrote your code. Your class should conform to the UITextFieldDelegate protocol and implement the textFieldDidBeginEditing method, like this:

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

}
like image 198
ridvankucuk Avatar answered Nov 11 '22 00:11

ridvankucuk


A way to select all text without adding a delegate:

present(vc, animated: true) {
    vc.textFields?.first?.selectAll(nil)
}
like image 41
zgjie Avatar answered Nov 11 '22 02:11

zgjie


Thanks, @ridvankucuk. Your solution works great.

But textfield delegate function can be simplified little bit:

func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.selectAll(nil)
}
like image 7
Ilia Liachin Avatar answered Nov 11 '22 01:11

Ilia Liachin