0

I have an alertview which displays a textfield which the user has to enter as mandatory. The problem is If user clicks "Authorise" without entering it the alertview get dismissed. I cant figure out a way of showing to user that it's mandatory without dismissing the alertview.

image

Code:

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)

}
Jeesson_7
  • 761
  • 1
  • 11
  • 38
  • 2
    you can disable the buttons initially and implement the textfield delegate method to check when to enable the buttons. – Sahil Sep 26 '16 at 07:15

3 Answers3

1

Set your class as a UIAlertViewDelegate and set your alrtView's delegate as your class.

Then do this

- (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
}
}
Shayan Jalil
  • 588
  • 5
  • 17
1
    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: 

enter image description here

enter image description here

EDIT:

If you don't want to enable or disable Authorize Action then you can use below code.

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


        })

And the alternative option to show messages only is Toast. https://github.com/scalessec/Toast

Neelam Pursnani
  • 246
  • 3
  • 17
  • can u explain this "#selector(self.textChanged(_:))" – Jeesson_7 Sep 26 '16 at 09:19
  • 1
    @Jeesson_7 it is same as TextField delegate method **shouldChangeCharactersInRange** which gives events of text change in textfield. – Neelam Pursnani Sep 26 '16 at 09:26
  • hey thank you for your effort. The problem is that I have this alert view displayed while clicking on a table row . I have added my code to my now edited question. – Jeesson_7 Sep 26 '16 at 11:09
0

You need to add gesture recognizer to the UIAlertController that triggers before the dismissal occurs for that you can refer below answer: Prevent UIAlertController to dismiss

else you can use below code:

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)
Anjali jariwala
  • 410
  • 5
  • 15