uialert objective example ios swift alert uialertcontroller

ios - example - uialertcontroller objective c



Compruebe en UIAlertController TextField para habilitar el botón (4)

Hay una manera mucho más simple sin usar el centro de notificación, de forma rápida:

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") }

Tengo un AlertController con un campo de texto y dos botones: CANCELAR y GUARDAR. Este es el código:

@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) }

Lo que quiero hacer es implementar una verificación en el campo de texto para deshabilitar el botón GUARDAR cuando el campo de texto está vacío, al igual que la Aplicación de Imágenes de iOS cuando desea crear un Nuevo Álbum. Por favor alguien me puede explicar que hacer?


Implementé una subclase de UIAlertController para agregar campos de texto convenientemente y habilitar y deshabilitar los botones asociados. La lógica básica es similar a la de Sourabh Sharma, pero todo está encapsulado en esta subclase para el orden. Esto debería ser útil si su proyecto involucra muchas de estas funcionalidades de alerta.

public class TextEnabledAlertController: UIAlertController { private var textFieldActions = [UITextField: ((UITextField)->Void)]() func addTextField(configurationHandler: ((UITextField) -> Void)? = nil, textChangeAction:((UITextField)->Void)?) { super.addTextField(configurationHandler: { (textField) in configurationHandler?(textField) if let textChangeAction = textChangeAction { self.textFieldActions[textField] = textChangeAction textField.addTarget(self, action: #selector(self.textFieldChanged), for: .editingChanged) } }) } @objc private func textFieldChanged(sender: UITextField) { if let textChangeAction = textFieldActions[sender] { textChangeAction(sender) } } }

Para usarlo, simplemente proporcione un bloque textChangeAction cuando agregue los campos de texto:

alert.addTextField(configurationHandler: { (textField) in textField.placeholder = "Your name" textField.autocapitalizationType = .words }) { (textField) in saveAction.isEnabled = (textField.text?.characters.count ?? 0) > 0 }

Para ver el ejemplo completo, vea la página de git .


Primero crearía el controlador de alerta con la acción de guardar inicialmente deshabilitada. Luego, al agregar el campo de texto inculpar una Notificación para observar su cambio en el controlador y en ese selector simplemente alternar la propiedad habilitada para guardar acciones.

Esto es lo que estoy diciendo:

//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 }

Estoy haciendo esto en otro proyecto: obtuve este patrón directamente de ejemplos de Apple. Tienen un proyecto de ejemplo muy bueno que describe algunos de estos patrones en los ejemplos de UICatalog: https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html


Solución actualizada de Swift 3.0 dada por @spoek

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") }