您是对的:如果用户可以点击警报中的按钮,则警报将被取消。所以你想阻止用户点击按钮!这只是禁用 UIAlertAction 按钮的问题。如果警报操作被禁用,用户无法点击它来关闭。
要将其与文本字段验证结合起来,请使用文本字段委托方法或操作方法(在创建文本字段的配置处理程序中配置)来根据已输入(或未输入)的文本适当地启用/禁用 UIAlertActions 。
这是一个例子。我们这样创建文本字段:
alert.addTextFieldWithConfigurationHandler {
(tf:UITextField!) in
tf.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
我们有一个“取消”操作和一个“确定”操作,并且我们将“确定”操作带入了禁用状态:
(alert.actions[1] as UIAlertAction).enabled = false
随后,除非文本字段中有一些实际文本,否则用户无法点击“确定”:
func textChanged(sender:AnyObject) {
let tf = sender as UITextField
var resp : UIResponder = tf
while !(resp is UIAlertController) { resp = resp.nextResponder() }
let alert = resp as UIAlertController
(alert.actions[1] as UIAlertAction).enabled = (tf.text != "")
}
EDIT以下是上述代码的当前版本(Swift 3.0.1 及更高版本):
alert.addTextField { tf in
tf.addTarget(self, action: #selector(self.textChanged), for: .editingChanged)
}
and
alert.actions[1].isEnabled = false
and
@objc func textChanged(_ sender: Any) {
let tf = sender as! UITextField
var resp : UIResponder! = tf
while !(resp is UIAlertController) { resp = resp.next }
let alert = resp as! UIAlertController
alert.actions[1].isEnabled = (tf.text != "")
}