Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check on UIAlertController TextField for enabling the button

I have an AlertController with a text field and two button: CANCEL and SAVE. This is the code:

@IBAction func addTherapy(sender: AnyObject)
{
    let addAlertView = UIAlertController(title: "New Prescription", message: "Insert a name for this prescription", preferredStyle: UIAlertControllerStyle.Alert)

    addAlertView.addAction(UIAlertAction(title: "Cancel",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addAction(UIAlertAction(title: "Save",
                                         style: UIAlertActionStyle.Default,
                                         handler: nil))

    addAlertView.addTextFieldWithConfigurationHandler({textField in textField.placeholder = "Title"})


    self.presentViewController(addAlertView, animated: true, completion: nil)


}

What I want to do is implement a check on the textfield for disabling the SAVE button when the textfield is empty just like Pictures Application of iOS when you want create a NewAlbum. Please someone can explain me what to do?

like image 975
Andorath Avatar asked Jun 29 '14 09:06

Andorath


People also ask

What is TextField in Swift?

A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).


2 Answers

There is a much simpler way without using notification center, in swift:

weak var actionToEnable : UIAlertAction?

func showAlert()
{
    let titleStr = "title"
    let messageStr = "message"

    let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)

    let placeholderStr =  "placeholder"

    alert.addTextField(configurationHandler: {(textField: UITextField) in
        textField.placeholder = placeholderStr
        textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
    })

    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in

    })

    let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
        let textfield = alert.textFields!.first!

        //Do what you want with the textfield!
    })

    alert.addAction(cancel)
    alert.addAction(action)

    self.actionToEnable = action
    action.isEnabled = false
    self.present(alert, animated: true, completion: nil)
}

func textChanged(_ sender:UITextField) {
    self.actionToEnable?.isEnabled  = (sender.text! == "Validation")
}
like image 94
ullstrm Avatar answered Oct 23 '22 05:10

ullstrm


I would first create the alertcontroller with the save action initially disabled. Then when adding the textfield inculde a Notification to observe its change in the handler and in that selector just toggle the save actions enabled property.

Here is what I am saying:

//hold this reference in your class
weak var AddAlertSaveAction: UIAlertAction?

@IBAction func addTherapy(sender : AnyObject) {

    //set up the alertcontroller
    let title = NSLocalizedString("New Prescription", comment: "")
    let message = NSLocalizedString("Insert a name for this prescription.", comment: "")
    let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
    let otherButtonTitle = NSLocalizedString("Save", comment: "")

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    // Add the text field with handler
    alertController.addTextFieldWithConfigurationHandler { textField in
        //listen for changes
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
    }


    func removeTextFieldObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
    }

    // Create the actions.
    let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
        NSLog("Cancel Button Pressed")
        removeTextFieldObserver()
    }

    let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in
        NSLog("Save Button Pressed")
        removeTextFieldObserver()
    }

    // disable the 'save' button (otherAction) initially
    otherAction.enabled = false

    // save the other action to toggle the enabled/disabled state when the text changed.
    AddAlertSaveAction = otherAction

    // Add the actions.
    alertController.addAction(cancelAction)
    alertController.addAction(otherAction)

    presentViewController(alertController, animated: true, completion: nil)
} 

    //handler
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
    let textField = notification.object as UITextField

    // Enforce a minimum length of >= 1 for secure text alerts.
    AddAlertSaveAction!.enabled = textField.text.utf16count >= 1
}

I am doing this in another project - I got this pattern directly from apple examples. They have a very good example project outlining a few of these patterns in the UICatalog examples: https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html

like image 28
Rufus Avatar answered Oct 23 '22 05:10

Rufus