在UIAlertController的文本字段中选择文本 [英] Select text in UIAlertController's text field

查看:99
本文介绍了在UIAlertController的文本字段中选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在显示UIAlertController之后,我需要立即选择文本字段的文本.但是,我在标准UITextField中选择文本的方式在这里行不通.

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

有什么想法吗?

推荐答案

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

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

}

这篇关于在UIAlertController的文本字段中选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆