我有一个带有4个UITextField的应用程序,如果UITextfield为空,我想显示一个UIAlert。我具有选择显示的UIAlert的功能,如下所示:
func displayMyAlertMessage(userMessage: String) {
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
}
我已经看过这个example了,因为我有UIPickerView来显示文本,所以无法使它工作。下面是我的didSelectRow代码:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if TrackTextField.isFirstResponder {
selectedTrack = tracks[row]
guard let track = selectedTrack?.isEmpty else {
displayMyAlertMessage(userMessage: "You have to fill in a track")
return
}
TrackTextField.text = String(track)
} else if firstTextField.isFirstResponder {
firstDriver = drivers[row]
firstTextField.text = firstDriver
} else if secondTextField.isFirstResponder {
secondDriver = drivers[row]
secondTextField.text = secondDriver
} else if thirdTextField.isFirstResponder {
thirdDriver = drivers[row]
thirdTextField.text = thirdDriver
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "getPredictor" {
let predictorVC = segue.destination as! UINavigationController
let vc = predictorVC.topViewController as! PredictorTableViewController
self.grandPrix.append(GrandPrix(granPrix: TrackTextField.text!, firstDriver: firstTextField.text!, secondDriver: secondTextField.text!, thirdDriver: thirdTextField.text!))
vc.grandPrix = self.grandPrix
}
}
我已经使用TrackTextField来测试警报是否起作用。当我单击Grandprix Predictor时,不会出现UIAlert。下面是与下一个UIViewController关联的函数。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "getPredictor" {
let predictorVC = segue.destination as! UINavigationController
let vc = predictorVC.topViewController as! PredictorTableViewController
self.grandPrix.append(GrandPrix(granPrix: TrackTextField.text!, firstDriver: firstTextField.text!, secondDriver: secondTextField.text!, thirdDriver: thirdTextField.text!))
vc.grandPrix = self.grandPrix
}
任何帮助将不胜感激。
答案 0 :(得分:1)
不应在选择器视图委托中进行检查。
答案实际上取决于您甚至想用来触发检查的内容。在用户应该填写所有四个文本字段之后,最有可能要在单击某些按钮时进行检查。
添加一个verifyInput
方法。像这样:
func verifyInput() -> Bool {
if TrackTextField.text?.isEmpty || firstTextField.text?.isEmpty || secondTextField.text?.isEmpty || thirdTextField.text?.isEmpty {
// at least one is empty, show your alert here
return false
} else {
return true // all good
}
}
然后从某个按钮处理程序或也许从verifyInput
调用shouldPerformSegue
。同样,这取决于您要用来触发检查的事件。
示例:
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// Only validate for this specific segue
if identifier == "getPredictor" {
return verifyInput()
} else {
return true
}
}
根据需要调整逻辑。