ios - 在 UIAlertController 的文本字段中选择文本

标签 ios swift uialertcontroller uialertaction

我需要在显示 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)
})

有什么想法吗?

最佳答案

我重写了你的代码。您的类应符合 UITextFieldDelegate 协议(protocol)并实现 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()
    }

}

关于ios - 在 UIAlertController 的文本字段中选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35991774/

相关文章:

ios 如何快速更改不同 View Controller 中另一个 View Controller 的内容

ios - UIToolbarButton 转至 UITabBarController 中的特定 View

Swift:如何使动画 SKShapenode 倒计时的计时器无效?

iphone - 使用仪器来查找代码中堆栈的溢出

ios - 如何使用他们的 iOS SDK 对多首 Spotify 歌曲进行排队

ios - 解密 AES-256-CBC 字符串(需要 IV、字符串/数据格式?)

ios - 添加第二个操作时 UIAlertController 崩溃 (SIGABRT)

ios - UIAlertController 背景色 iOS10

ios - UIAlertView 首先弃用 IOS 9

ios - 我可以发布带有基本 SDK iOS 7.0 和 Today 扩展的应用程序吗?