【问题标题】:Check on UIAlertController TextField for enabling the button检查 UIAlertController TextField 以启用按钮
【发布时间】:2014-08-19 22:01:34
【问题描述】:

我有一个带有文本字段和两个按钮的 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)


}

我想要做的是对文本字段进行检查,以在文本字段为空时禁用“保存”按钮,就像您想要创建新专辑时 iOS 的图片应用程序一样。请有人可以解释我该怎么做?

【问题讨论】:

    标签: ios swift alert uialertcontroller


    【解决方案1】:

    有一个更简单的方法,不使用通知中心,快速:

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

    【讨论】:

    • 在 Swift 3 代码中,缺少actionToEnable 变量定义
    • 太棒了..!很酷的答案
    【解决方案2】:

    我将首先创建警报控制器,并在最初禁用保存操作。然后在添加文本字段时包含一个通知以观察其在处理程序中的变化,并在该选择器中切换保存操作启用属性。

    这就是我要说的:

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

    我在另一个项目中这样做 - 我直接从苹果示例中获得了这种模式。他们有一个很好的示例项目,在 UICatalog 示例中概述了其中一些模式:https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html

    【讨论】:

    • 你帮了我很多忙!非常感谢!
    • 使用通知过于笨拙(而且不可靠,而且工作量太大)。这就是为什么有文本字段委托和操作的原因。在这里查看我的答案:stackoverflow.com/a/25628065/341994
    • 马特的回答更好
    • 它给出错误:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[Naina.SearchVillageTableViewController handleTextFieldTextDidChangeNotification:]:无法识别的选择器发送到实例 0x7f802dc41f50'
    【解决方案3】:

    @spoek 给出的 Swift 3.0 更新解决方案

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

    【讨论】:

    • 真的很有帮助。谢谢:)
    【解决方案4】:

    我实现了 UIAlertController 的子类,用于方便地添加文本字段以及相关的按钮启用和禁用。基本逻辑与 Sourabh Sharma 类似,但一切都封装在这个子类中以保持整洁。如果您的项目涉及大量此类警报功能,这应该会有所帮助。

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

    要使用它,只需在添加文本字段时提供一个 textChangeAction 块:

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

    有关完整示例,请参阅the git page

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多