我正在尝试在我的应用程序中设计一个视图,当UITextField内的文本与某个正则表达式不匹配时,该视图显示错误UILabel.除了当我的UITextField包含无效条目然后点击屏幕以关闭键盘时,一切正常.键盘解散后,UITextField移动到我的UITextView(红色文本)之上,我找不到原因.我在我的代码中设置了断点,但似乎在键盘解除后我的代码都没有执行.任何帮助表示赞赏.
// // ViewController.swift // KeyboardLabel // import UIKit class ViewController: UIViewController { @IBOutlet var titleLabel:UILabel! @IBOutlet var errorLabel:UITextView! @IBOutlet var textBox:UITextField! @IBOutlet var createButton:UIButton! var deltaHeight:CGFloat! var beenMoved = true override func viewDidLoad() { super.viewDidLoad() // Register for notifications when the text in the text field is changed NSNotificationCenter.defaultCenter().addObserver(self,selector: "validateText",name: UITextFieldTextDidChangeNotification,object: textBox) // Add a gesture recognizer to dismiss the keyboard view.addGestureRecognizer(UITapGestureRecognizer(target: self,action: "dismissKeyboard")) // Set the text of the labels titleLabel.text = "Container Number:" errorLabel.text = "Error,Invalid container number.\nRe-enter number." // Calculate the height to move the text field and button deltaHeight = errorLabel.frame.size.height + 8.0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { textBox.resignFirstResponder() } func validateText() { dispatch_async(dispatch_get_main_queue(),{ // Regular expression for determining whether the text is valid let predicate = NSPredicate(format: "SELF MATCHES %@","[a-zA-Z0-9#]+") let empty = self.textBox.text!.isEmpty let valid = predicate.evaluateWithObject(self.textBox.text) // If the string is valid if valid || empty { // If the view has been moved down if(!self.beenMoved) { // Hide the error label then move the text field and create button up self.errorLabel.hidden = true UIView.animateWithDuration(0.4,animations: { self.textBox.frame.origin.y -= self.deltaHeight self.createButton.frame.origin.y -= self.deltaHeight }) // Flip the flag self.beenMoved = true } } // If the string is invalid else { // If the view has been moved up if(self.beenMoved) { // Show the error label then move the text field and create button down UIView.animateWithDuration(0.4,animations: { self.textBox.frame.origin.y += self.deltaHeight self.createButton.frame.origin.y += self.deltaHeight },completion: { (flag:Bool) in self.errorLabel.hidden = false }) // Flip the flag self.beenMoved = false } } // If the text field is empty if empty { // Disable the create button self.createButton.enabled = false } else { // Enable the create button self.createButton.enabled = true } }) } }