Elye
Elye

Reputation: 60111

How can I add custom textField to my alert?

I can add textField to my alert as shown below using alert.addTextField()

        let alert = UIAlertController(title: "Title", message: "Subtitle", preferredStyle: UIAlertController.Style.alert)
        alert.addTextField()
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: { _ in
            print(alert.textFields?[0].text ?? "")
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)

However, if I have a custom textField, like CurrencyField as shared in https://stackoverflow.com/a/29783546/3286489, how could I add that to my alert (instead of just having a generic TextField)?

Upvotes: 0

Views: 1053

Answers (1)

mattsven
mattsven

Reputation: 23283

The Holy Path

The Apple-given API doesn't allow for you to use a custom subclass of UITextField. It does, however, allow you to customize the UITextField:

alert.addTextField { textField in
    // customize text field
}

You'll have to try and port the functionality of your CurrencyView over, having only access to the APIs available by default on UITextField.

The Unholy Path

⚠️ Disclaimer: This is a Bad Idea. Using vendor APIs in ways they weren't intended to makes your code and application less stable.

Now that we've got that out of the way: you could also add a view directly to the default UITextField. You'd have to disable interaction/editing on the original UITextField, though, and make sure it only goes to your custom text field.

If you really wanted to go to the dark side, you could swizzle UITextField and force your CurrencyView to be initialized, but, once again, this is a Bad Idea.

Upvotes: 2

Related Questions