0

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

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

2

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.

mattsven
  • 22,305
  • 11
  • 68
  • 104
  • Excellent explanation @mattsven. Indeed by looking at the `open class UIAlertController : UIViewController`, doesn't seem to have a way to custom it... even the `open var textFields: [UITextField]? { get }` is set to `get` only. – Elye Feb 23 '20 at 00:35
  • What I mean `custom it` above, refers to assigned a custom made UITextField... sorry for the confusion – Elye Feb 23 '20 at 01:06