Problems with getting text from UIAlertView textfield

…衆ロ難τιáo~ 提交于 2019-11-29 00:16:37
iRiziya

You may go with UIAlertController instead of UIAlertView.

I've already implemented and tested too using UIAlertController for what you actually want. Please try the following code

    var tField: UITextField!

    func configurationTextField(textField: UITextField!)
    {
        print("generating the TextField")
        textField.placeholder = "Enter an item"
        tField = textField
    }

    func handleCancel(alertView: UIAlertAction!)
    {
        print("Cancelled !!")
    }

    var alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: .Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{ (UIAlertAction) in
        print("Done !!")

        print("Item : \(self.tField.text)")
    }))
    self.presentViewController(alert, animated: true, completion: {
        print("completion block")
    })

You will have to implement the UIAlertViewDelegate's

optional func alertView(_ alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)

For SWIFT 3

@IBAction func ForgotPassword(_ sender: Any) {

    let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
        if let field = alertController.textFields![0] as? UITextField {

            // store and use entered data

        } else {

            print("please enter email id")
        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in
        textField.placeholder = "Email"
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)

}

I hope it will help someone else :)

For iOS 8+ you should use UIAlertController instead of UIAlertView. To support iOS 7 you should implement (UIAlertViewDelegate):

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
{
    //...
    let textField = alertView.textFieldAtIndex(0)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!