某些時候,要像類似蘋果商店下載東西時候輸入賬號密碼驗證可以直接使用系統(tǒng)提供的彈窗控件。大家也可以根據(jù)實時檢測輸入的值來做進(jìn)一步優(yōu)化..

實時檢測
@IBAction func buttonClcik(sender: UIButton) {
let alert = UIAlertController(
title: "請輸入賬號密碼:", message: nil, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler {
(tf:UITextField) in
tf.placeholder = "賬號"
tf.tag = 0
tf.addTarget(self,
action: #selector(ViewController.textChanged(_:)), forControlEvents: .EditingChanged)
}
alert.addTextFieldWithConfigurationHandler {
(tf:UITextField) in
tf.placeholder = "密碼"
tf.keyboardType = .NumberPad
tf.tag = 1
tf.addTarget(self,
action: #selector(ViewController.textChanged(_:)), forControlEvents: .EditingChanged)
}
func handler(act:UIAlertAction) {
let tf = alert.textFields![0]
let tf2 = alert.textFields![1]
print("賬號:\(tf),密碼:\(tf2)")
}
alert.addAction(UIAlertAction(
title: "取消", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(
title: "確定", style: .Default, handler: handler))
self.presentViewController(alert, animated: true, completion: nil)
}
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].enabled = (tf.text != "")
switch tf.tag {
case 0:
print("當(dāng)前輸入賬號:\(tf.text!)")
case 1:
print("當(dāng)前輸入密碼:\(tf.text!)")
default:
break
}
}