Problems with getting text from UIAlertView textfield

前端 未结 4 884
滥情空心
滥情空心 2020-12-15 13:08

In my application I want a alert with a textfield. After clicking on \"Done\" I want to save the textfield input in a String. After clicking on \"Cancel\" I want only to clo

相关标签:
4条回答
  • 2020-12-15 13:31

    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")
        })
    
    0 讨论(0)
  • 2020-12-15 13:38

    You will have to implement the UIAlertViewDelegate's

    optional func alertView(_ alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
    
    0 讨论(0)
  • 2020-12-15 13:38

    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)
    }
    
    0 讨论(0)
  • 2020-12-15 13:54

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

    0 讨论(0)
提交回复
热议问题