Select text in UIAlertController's text field

这一生的挚爱 提交于 2019-12-10 03:34:38

问题


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?


回答1:


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

}



回答2:


Thanks, @ridvankucuk. Your solution works great.

But textfield delegate function can be simplified little bit:

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



回答3:


A way to select all text without adding a delegate:

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


来源:https://stackoverflow.com/questions/35991774/select-text-in-uialertcontrollers-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!