Swift NSNotificationCenter?

我试图让UITextViewTextDidChangeNotification工作。 我是使用NSNotificationCenter的新手,所以我很难理解到底发生了什么。 我在故事板中有一个UITextView,并且在ViewController类中为它创build了一个IBOutlet,并将其命名为textView。

这是我的viewDidLoad函数:

override func viewDidLoad() { super.viewDidLoad() origin = self.view.frame.origin.y if let field = textView{ field.placeholder = placeholder field.layer.cornerRadius = 8 field.layer.borderWidth = 0.5 field.layer.borderColor = UIColor.grayColor().CGColor NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyPressed:"), name:UITextFieldTextDidChangeNotification, object: nil); } NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } 

键盘通知很好用。 据我了解,他们调用与select器相同的名称的函数。 那是对的吗? 还是有更多的事情在这里? 我做了一个叫做keyPressed的函数,它把一个NSNotification作为参数,但是这个函数从来没有被调用,而当我使用键盘的时候,keyboardWillShow和keyboardWillHide函数被调用。 有人可以解释发生了什么事吗?

好的,所以我想出了一个解决scheme。 我需要在textViewDidChange函数中发布通知。 我用这个做了:

 NSNotificationCenter.defaultCenter().postNotificationName("keyPressed", object: nil) 

然后我认识到我的viewDidLoad函数中的通知:

 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyPressed:"), name:"keyPressed", object: nil); 

然后我在我的viewDidLoad函数下做了这个函数:

 func keyPressed(sender: NSNotification) { } 
Interesting Posts