如何在Swift中将TextField添加到UIAlertController [英] How to add TextField to UIAlertController in Swift

查看:237
本文介绍了如何在Swift中将TextField添加到UIAlertController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示带有UITextViewUIAlertController.当我添加行时:

I am trying to show a UIAlertController with a UITextView. When I add the line:

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    }        

我收到Runtime错误:

致命错误:解开可选值时意外发现nil

fatal error: unexpectedly found nil while unwrapping an Optional value

    let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)

    //cancel button
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //cancel code
    }
    alertController.addAction(cancelAction)

    //Create an optional action
    let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
        let text = (alertController.textFields?.first as! UITextField).text
        println("You entered \(text)")
    }
    alertController.addAction(nextAction)

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        textField.textColor = UIColor.greenColor()
    }
    //Present the AlertController
    presentViewController(alertController, animated: true, completion: nil)

这通过IBAction出现在我的ViewController内部.

This is presented inside my ViewController via an IBAction.

我已经从此处下载了代码,并且运行正常.我将该方法复制并粘贴到我的代码中,但它中断了.最后一行中的 self 不会影响

I have downloaded the code from here and it works fine. I copied and pasted that method into my code and it breaks. The presence of self on the last line has no impact.

推荐答案

所以我开始检查看看我的代码和工作代码可能有什么不同.我注意到我的ViewController扩展了

So I started checking to see what could possibly have been different in my code to the working code. I noticed that my ViewController extends

UITextFieldDelegate

这显然意味着我需要设置任何子UITextView的委托:

Which apparently means that I need to set the delegate of any child UITextView:

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    searchTextField = textField
    searchTextField?.delegate = self //REQUIRED
    searchTextField?.placeholder = "Enter your search terms"
}

这篇关于如何在Swift中将TextField添加到UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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