Skip to content

6. Single Text Field Alerts

Gabriel Theodoropoulos edited this page Apr 17, 2019 · 1 revision

Single text field alerts

Having text fields in alert controllers is not unusual, and of course that kind of alert could not be missing from GTAlertCollection. In fact, there are two methods you can use to present alerts with text fields. The first one which we'll see in this part is a convenient method that adds one text field to the alert only, while the second one allows you to add as many text fields as you want.

Let's get started, and let's see how to present an alert with a single text field in it:

GTAlertCollection.shared.presentSingleTextFieldAlert(withTitle: "Editor", message: "Feel free to type something:", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", configurationHandler: { (textField, didFinishConfiguration) in

    if let textField = textField {
        // Configure the textfield properties.

        // Always call the following to let the alert controller appear.
        didFinishConfiguration()
    }

}) { (textField) in
    if let textField = textField {
        // Do something with the textfield's text...
    }
}

Single-textfield alert

The alert has two default action buttons, one for accepting the changes, and one to cancel. You can override the default titles ("Done" and "Cancel" respectively) for both.

The method above provides two interesting action handlers (closures). The first one is used to configure the text field's properties before the alert gets presented. Always follow the example shown above, and always make sure that the textField is not nil before accessing any of its properties.

And here's a really important rule:

After having finished configuring the text field, always call the didFinishConfiguration closure to allow the alert to be presented!

didFinishConfiguration is a closure (as stated already), which you can name it however you want, but you must mandatorily call it once you're done with the text field configuration. Omitting that will lead to no alert presentation at all.

The second action handler returns the text field once user has finished editing it and the Done action button has been tapped. Once again, unwrap before using it, and then extract the text or whatever else you want out of it.

Clone this wiki locally