简体   繁体   中英

Swift: how to add a custom input view in an UIAlertController?

I'm adding a login form under a UIAlertController, to get some xml data from a web page. I need to enter a user name, a password and a date. To do this I add 3 text fields to an UIAlertController's instance using .addTextFieldWithConfigurationHandler method. In one of them I change the input view to be an UIDatePicker. The deal is I need to add a UIToolBar with an UIBarButton item to make a "Done" button to finish the input. Everything is done well, except I cannot access the showSelectedDate() function (the function is never called) to dismiss the inputView and set the UITextField.text property with the date. The button is there, but it is un usable.

Here is my code.

loginDeCompraMercadoWebAlertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        //Declare my inputView, DatePicker and UIToolBar
        let toolBar = UIToolbar(frame: CGRectMake(0, 0, textField.frame.size.width, textField.frame.size.height))
        let datePicker = UIDatePicker()
        let formatter = NSDateFormatter()
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "showSelectedDate")
        let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        toolBar.setItems([doneButton, space], animated: true)

        //Setup inputView and placeholders
        textField.placeholder = "Fecha de Compra"
        textField.inputView = datePicker
        textField.inputAccessoryView = toolBar
        textField.text = formatter.stringFromDate(datePicker.date)
    }

Thanks a lot, and if you have any suggestions please make me know.

I'm a novice (and not full time) programmer, and if there is any way I can be useful to someone, please let me know too.

One of the properties of a UIAlertController is that when it is shown, the user will not be able to interact with any of the UI elements that are in the background. So anything that you want the user to be able to use when the alert controller is up, needs to be a part of that alert controller.

Here is a great tutorial by NSHipster that goes over alert controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM