仅当用户使用以下代码行输入某些输入时,我才希望启用警报操作:
var alert: UIAlertController!
func alertBeitrageMelden(postId: String){
self.alert = UIAlertController(title: "Beitrag melden", message: "Wieso möchtest du den Beitrag melden?", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Melden", style: .default) { (action) in
if let text = self.alert.textFields?.first?.text, text.count > 0 {
let postTime = Date().timeIntervalSince1970
let ref = Database.database().reference().child("gemeldeteBeitraege").child(postId)
ref.setValue(["postId": postId, "reason": text, "time": postTime])
ProgressHUD.showSuccess("Der Beitrag wurde gemeldet", interaction: false)
}
}
let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel) { (action) in
}
alert.addTextField { (textField) in
textField.placeholder = ""
textField.delegate = self
}
alert.addAction(defaultAction)
alert.addAction(cancelAction)
self.present(alert, animated: true) {
}
}
在这里,我检查用户是否输入了以下内容:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.count)! > 0 {
self.alert.actions[0].isEnabled = true
}else{
self.alert.actions[0].isEnabled = false
}
return true;
}
但是它仍然无法正常工作。
在此先感谢您的帮助!
答案 0 :(得分:2)
这样做
textField.addTarget(self, action: #selector(self.textEdited), for: .editingChanged)
@objc func textEdited(_ textField:UITextField) {
if textField.text!.count > 0 {
alert.actions.first?.isEnabled = true
}else{
alert.actions.first?.isEnabled = false
}
}
添加此行将在最初将其禁用
alert.actions.first?.isEnabled = false
self.present(alert, animated: true)