我做了一個AlertViewController
與textField
,要求用戶輸入數據模型的新項目的名稱。禁用UIAlertView中的按鈕,而文本字段爲空
所以我想保持提交按鈕禁用,而文本字段爲空。在其他情況下,當我創建@IBOutlet
在ViewController
從故事板textfield我可以只使用UITextFieldDelegate
協議中的一些方法,並解決問題沒有你的幫助。
但現在我不能。
我做了一個AlertViewController
與textField
,要求用戶輸入數據模型的新項目的名稱。禁用UIAlertView中的按鈕,而文本字段爲空
所以我想保持提交按鈕禁用,而文本字段爲空。在其他情況下,當我創建@IBOutlet
在ViewController
從故事板textfield我可以只使用UITextFieldDelegate
協議中的一些方法,並解決問題沒有你的幫助。
但現在我不能。
註冊文本字段更改通知和驗證文本字段有:
@IBAction func showAlert(sender: AnyObject) {
var alert = UIAlertController(title: "New user",
message: "Add a new user",
preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save",
style: .Default) { (action: UIAlertAction!) -> Void in
println("do your stuff here")
}
saveAction.enabled = false
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction!) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textFieldName: UITextField!) in
textFieldName.placeholder = "Enter full name"
}
alert.addTextFieldWithConfigurationHandler {
(textFieldEmail: UITextField!) in
textFieldEmail.placeholder = "Enter valid email adress"
textFieldEmail.keyboardType = .EmailAddress
}
// adding the notification observer here
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object:alert.textFields?[0],
queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
let textFieldName = alert.textFields?[0] as! UITextField
let textFieldEmail = alert.textFields![1] as! UITextField
saveAction.enabled = self.isValidEmail(textFieldEmail.text) && !textFieldName.text.isEmpty
}
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object:alert.textFields?[1],
queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
let textFieldEmail = alert.textFields?[1] as! UITextField
let textFieldName = alert.textFields?[0] as! UITextField
saveAction.enabled = self.isValidEmail(textFieldEmail.text) && !textFieldName.text.isEmpty
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert,
animated: true,
completion: nil)
}
// email validation code method
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
if let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) as NSPredicate? {
return emailTest.evaluateWithObject(testStr)
}
return false
}
在viewDidLoad方法
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(
self,
selector: "textFieldTextChanged:",
name:UITextFieldTextDidChangeNotification,
object: nil
)
添加此代碼,並在視圖控制器
這種方法func textFieldTextChanged(sender : AnyObject) {
//your code
}
謝謝,我想過使用通知,但有人懷疑爲我的小任務使用如此強大的機制:) –
檢查這個鏈接,它可能會幫助你:http://useyourloaf.com/blog/uialertcontroller-changes-in-ios-8/ –
謝謝,非常有用,但翻譯成我的母語需要時間 - 很快,但我已經看到答案... –