我有一个带文本字段和两个按钮的AlertController:CANCEL和SAVE。这是代码:
@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) }
我想做的是在文本字段上执行检查,以在文本字段为空时禁用SAVE按钮,就像要创建NewAlbum的iOS图片应用程序一样。请有人可以解释我该怎么办?
我首先将创建一个最初禁用保存操作的alertcontroller。然后,在添加文本字段时,请插入一个Notification,以观察其在处理程序中的更改,并在该选择器中切换“启用保存操作”属性。
我的意思是:
//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 }
我正在另一个项目中执行此操作- 我直接从Apple示例获得了此模式。他们有一个很好的示例项目,概述了UICatalog示例中的一些模式:https : //developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html