11

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

这是我尝试过的,但我似乎无法让它发挥作用。

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

有任何想法吗?

4

3 回答 3

15

我已经重写了你的代码。您的类应符合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()
    }

}
于 2016-03-14T15:50:46.160 回答
8

一种在不添加委托的情况下选择所有文本的方法:

present(vc, animated: true) {
    vc.textFields?.first?.selectAll(nil)
}
于 2017-12-21T16:58:02.007 回答
7

谢谢,@ridvankucuk。您的解决方案效果很好。

但是 textfield 委托功能可以稍微简化一下:

func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.selectAll(nil)
}
于 2016-10-31T11:06:45.253 回答