Search code examples
swift2xcode7alertuipickerview

Error alert in uipickerview options


I'm working in these lines trying to show an "Error" message if the user forgot to fill the username label or choose an option from the PickerView ("-- Choose an option please --"), but, when I run this, it takes also the other options from the picker view as an error.

If the user choose A,B,C,D it's okay. I just want to define the first one ("-- Choose an option please --") as an error, but it doesn't works.


class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

let userRole:[String] = ["-- Choose an option please --", "A", "B", "C", "D"]
var selectedOption:String?

@IBOutlet weak var usernameLabel: UITextField!
@IBOutlet weak var pickerRoleLabel: UIPickerView!

@IBAction func continueButton(sender: AnyObject) {
    if usernameLabel.text == "" || userRole[0] == "-- Choose an option please --" {
        let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
            self.dismissViewControllerAnimated(true, completion: nil)
        }))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

How can I improve this? Thanks in advance!


Solution

  • You could always ensure your "-- Choose an option please --" string as first item. So you can just test if the value of the desired component with UIPickerView´s selectedRowInComponent method is bigger than "0". If "0" is returned from this method, means your first position is selected, but if you receive "-1", no value was selected in your picker. Any value bigger than "0" you can considerate as a valid value.

    selectedRowInComponent(_ component: Int)

    @IBAction func continueButton(sender: AnyObject) {
    
        //If you
    
        if usernameLabel.text == "" || myPickerView.selectedRowInComponent(0) < 1 {
            let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
                self.dismissViewControllerAnimated(true, completion: nil)
            }))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }