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