有没有一种方法可以使用 swift 在 alertview 内的文本字段中提供验证

Posted

技术标签:

【中文标题】有没有一种方法可以使用 swift 在 alertview 内的文本字段中提供验证【英文标题】:Is there a way of providing validation in the textfield which is inside alertview using swift 【发布时间】:2016-09-26 07:05:14 【问题描述】:

我有一个警报视图,它显示一个用户必须输入的文本字段。问题是如果用户单击“授权”而不输入它,则警报视图将被解雇。我想不出一种在不关闭警报视图的情况下向用户显示它是强制性的方法。

代码:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)

    print("You selected cell #\(self.empNameArr[indexPath.row])!")
    let alertController = UIAlertController(title: "OD Authorise", message: "", preferredStyle: UIAlertControllerStyle.Alert)

    let AUTHORISE = UIAlertAction(title: "AUTHORISE", style: UIAlertActionStyle.Default, handler: 
        alert -> Void in

        let firstTextField = alertController.textFields![3] as UITextField
        print("<><><><><><>",firstTextField.text)

    )

    let DENY = UIAlertAction(title: "DENY", style: UIAlertActionStyle.Default, handler: 
        (action : UIAlertAction!) -> Void in

    )

    let CANCEL = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.Default, handler: 
        (action : UIAlertAction!) -> Void in

    )


    alertController.addTextFieldWithConfigurationHandler  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " Employee Name :\(self.empNameArr[indexPath.row]) "
        txtRemarks.userInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.None

    

    alertController.addTextFieldWithConfigurationHandler  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " From Date :\(self.leavDateArr[indexPath.row]) "
        txtRemarks.userInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.None

    
    alertController.addTextFieldWithConfigurationHandler  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " To Date :\(self.ToDate[indexPath.row]) "
        txtRemarks.userInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.None

    



    alertController.addTextFieldWithConfigurationHandler  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " Leave reason :\(self.Reason[indexPath.row]) "
        txtRemarks.userInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.None

    


    alertController.addTextFieldWithConfigurationHandler  (txtRemarks : UITextField!) -> Void in
        txtRemarks.placeholder = "Enter Your Remarks"
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 15)
        txtRemarks.userInteractionEnabled=true
        txtRemarks.borderStyle = UITextBorderStyle.Line
        txtRemarks.textAlignment = NSTextAlignment.Center

    


    alertController.addAction(AUTHORISE)
    alertController.addAction(DENY)
    alertController.addAction(CANCEL)

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


【问题讨论】:

您可以先禁用按钮,然后实现文本字段委托方法来检查何时启用按钮。 【参考方案1】:

将您的类设置为 UIAlertViewDelegate 并将您的 alrtView 的委托设置为您的类。

然后这样做

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
if (buttonIndex == 1) 
    NSString *name = [alertView textFieldAtIndex:0].text;
    // Here check for validation. If the text is empty disable button or however you would like to handle it


【讨论】:

这个问题被标记为 Swift,而不是 Objective-C。【参考方案2】:
    class ViewController: UIViewController,UITextFieldDelegate
    

        override func viewDidLoad() 
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        

        override func didReceiveMemoryWarning() 
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        

        var authorizeaction:UIAlertAction?

        @IBAction func tapBtnaction(sender: AnyObject)
        
            let titleStr = "title"
            let messageStr = "message"

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

            let placeholderStr =  "Enter your Remarks"

            alert.addTextFieldWithConfigurationHandler((textField: UITextField) in
                textField.placeholder = placeholderStr
                textField.addTarget(self, action: #selector(self.textChanged(_:)), forControlEvents: .EditingChanged)
            )

            let authorize = UIAlertAction(title: "Authorize", style: UIAlertActionStyle.Default, handler:  (_) -> Void in

            )

            let deny = UIAlertAction(title: "Deny", style: UIAlertActionStyle.Default, handler:  (_) -> Void in
                let textfield = alert.textFields!.first!

                //Do what you want with the textfield!
            )
            let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:  (_) -> Void in
                let textfield = alert.textFields!.first!

                //Do what you want with the textfield!
            )
            alert.addAction(cancel)
            alert.addAction(authorize)
            alert.addAction(deny)

            //self.actionToEnable = action
            authorizeaction = authorize
            authorizeaction!.enabled = false
            self.presentViewController(alert, animated: true, completion: nil)


        
        func textChanged(sender:UITextField)
        

           if sender.text?.characters.count > 0
        
        authorizeaction?.enabled = true
        
        else
        
            authorizeaction?.enabled = false
        

        

    
Output: 

编辑:

如果您不想启用或禁用授权操作,则可以使用以下代码。

let authorize = UIAlertAction(title: "Authorize", style: UIAlertActionStyle.Default, handler:  (_) -> Void in
            if let textfield : UITextField = alert.textFields![0]
            
                if textfield.text?.characters.count == 0 
                    //empty

                    self.presentViewController(alert, animated: true, completion:  
                        let tempAlert = UIAlertController(title: "Error", message: "Please Enter remarks", preferredStyle: UIAlertControllerStyle.Alert)
                        tempAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler:  (action) in

                        ))

                        alert.presentViewController(tempAlert, animated: true, completion: nil)
                    )

                 else 
                    //authorize
                
            


        )

仅显示消息的替代选项是 Toast。 https://github.com/scalessec/Toast

【讨论】:

你能解释一下这个“#selector(self.textChanged(_:))” @Jeesson_7 它与 TextField 委托方法 shouldChangeCharactersInRange 相同,它在文本字段中提供文本更改事件。 嘿,谢谢你的努力。问题是我在单击表格行时显示了此警报视图。我已将我的代码添加到我现在编辑的问题中。【参考方案3】:

您需要将手势识别器添加到在解雇发生之前触发的 UIAlertController 为此,您可以参考以下答案: Prevent UIAlertController to dismiss

否则你可以使用下面的代码:

let alertController = UIAlertController(title: "OD Authorise", message: "", preferredStyle: UIAlertControllerStyle.alert)

    let AUTHORISE = UIAlertAction(title: "AUTHORISE", style: UIAlertActionStyle.default, handler: 
        alert -> Void in

        let firstTextField = alertController.textFields![4] as UITextField
        if firstTextField.text?.count == 0
        
            //print("Please enter your remark first")
            SVProgressHUD.showError(withStatus: "Please enter your remark first")
            self.present(alertController, animated: true, completion: nil)

            return
        
        print("<><><><><><>",firstTextField.text ?? "")

    )

    let DENY = UIAlertAction(title: "DENY", style: UIAlertActionStyle.default, handler: 
        (action : UIAlertAction!) -> Void in

    )

    let CANCEL = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.default, handler: 
        (action : UIAlertAction!) -> Void in

    )


    alertController.addTextField  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " Employee Name : YOUR ARRAY OBJECT"//\(self.empNameArr[indexPath.row]) "
        txtRemarks.isUserInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.none

    

    alertController.addTextField  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " From Date : YOUR ARRAY OBJECT"//\(self.leavDateArr[indexPath.row]) "
        txtRemarks.isUserInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.none

    
    alertController.addTextField  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " To Date : YOUR ARRAY OBJECT"//\(self.ToDate[indexPath.row]) "
        txtRemarks.isUserInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.none

    



    alertController.addTextField  (txtRemarks : UITextField!) -> Void in
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 11)
        txtRemarks.text = " Leave reason : YOUR ARRAY OBJECT"//\(self.Reason[indexPath.row]) "
        txtRemarks.isUserInteractionEnabled=false
        txtRemarks.borderStyle = UITextBorderStyle.none

    


    alertController.addTextField  (txtRemarks : UITextField!) -> Void in
        txtRemarks.placeholder = "Enter Your Remarks"
        txtRemarks.font = UIFont(name: (txtRemarks.font?.fontName)!, size: 15)
        txtRemarks.isUserInteractionEnabled=true
        txtRemarks.borderStyle = UITextBorderStyle.line
        txtRemarks.textAlignment = NSTextAlignment.center

    


    alertController.addAction(AUTHORISE)
    alertController.addAction(DENY)
    alertController.addAction(CANCEL)

    self.present(alertController, animated: true, completion: nil)

【讨论】:

以上是关于有没有一种方法可以使用 swift 在 alertview 内的文本字段中提供验证的主要内容,如果未能解决你的问题,请参考以下文章

在 SWIFT 4 中更改弹出框颜色

IOS swift TableView有没有一种方法可以重用它们

有没有一种简单的方法可以暂时禁用 Swift 中精灵的物理体? (雪碧套件)

如何全局导入 Swift 框架?

是否有一种特定的方法在Swift中使用元组作为set元素?

在 GameScene 中显示 UIAlertController (SpriteKit/Swift)