Problems with getting text from UIAlertView textfield

前端 未结 4 888
滥情空心
滥情空心 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")
        })
    

提交回复
热议问题