pmusolino / PMAlertController

PMAlertController is a great and customizable alert that can substitute UIAlertController
MIT License
2.53k stars 186 forks source link

Require textfield value #81

Closed delucamike closed 5 years ago

delucamike commented 5 years ago

Is it possible to require a value in the text field before the user can click an action button? Additionally, can you specify a min/max length to the text?

pmusolino commented 5 years ago

I'm sorry but at the moment it's not possible, because when you tap a button automatically it dismisses the alert. About the text, yes, you can edit how text field works.

scottpchow23 commented 5 years ago

A solution to this that doesn't rely on the library can be found here:

https://nshipster.com/uialertcontroller/

olliekav commented 4 years ago

Though I'd post this here incase it helps anyway else out trying to do this and I've just switched our alerts to PMAController. I'm pretty new to swift so might be better ways to do it :)

Add the textfield as a subview of the content stack view (so I can have horizontal buttons), with an editing changed UIControl event

let textField = TextField(frame: CGRect(x: 0, y: 0, width: 230, height: 40))
textField.placeholder = "Enter your email address"
textField.backgroundColor = ColorCompatibility.lightBackground
textField.layer.cornerRadius = 8
textField.font = UIFont.systemFont(ofSize: 15)
textField.keyboardType = UIKeyboardType.emailAddress
textField.autocapitalizationType = .none
textField.accessibilityIdentifier = "forgotPasswordInput"
textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(field:)), for: UIControl.Event.editingChanged)
alert.alertContentStackView.addArrangedSubview(textField)

I'm only using a tag here as an example, but add your button action as you normally would and set i to disabled.

let submitAction = PMAlertAction(title: "Submit", style: .default, action: {() in }
submitAction.tag = 0xAC
submitAction.isEnabled = false

Now you can listen for changes on the textfield and decide what to do...

@objc func alertTextFieldDidChange(field: UITextField){
        let alertController: PMAlertController = self.presentedViewController as! PMAlertController
        if let submitAction = alertController.view.viewWithTag(0xAC) as? UIButton {
            submitAction.isEnabled = (field.text?.isEmail)
        }
    }