uipickerview 选项中的错误警报

Error alert in uipickerview options

如果用户忘记填写用户名标签或选择选项,我将在这些行中尝试显示 "Error" 消息来自 PickerView(“-- 请选择一个选项 --”),但是,当我 运行 这样做时,它也会将选择器视图中的其他选项视为错误。

如果用户选择A,B,C,D就可以了。我只想将第一个 ("-- 请选择一个选项 --") 定义为错误,但它不起作用。


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

我该如何改进? 提前致谢!

您始终可以确保您的“-- 请选择一个选项--”字符串作为第一项。因此,您可以使用 UIPickerView´s selectedRowInComponent 方法测试所需组件的值是否大于 "0"。 =20=]。 如果从该方法返回 "0"",表示您选择了第一个位置,但如果您收到 "-1",则没有选择任何值在你的选择器中。任何大于“0”的值都可以视为有效值。

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