Swift NSNotificationCenter?

2019-03-05 18:19发布

问题:

I'm trying to get the UITextViewTextDidChangeNotification to work. I'm new to using the NSNotificationCenter, so I'm having a hard time understanding what's going on exactly. I have a UITextView in a storyboard, and I've created an IBOutlet for it in my ViewController class and called it textView.

This is my viewDidLoad function:

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);
}

The keyboard notifications work great. To my understanding, they call a function with the same name as the selector. Is that correct? Or is there something more going on here? I made a function called keyPressed that took an NSNotification as a parameter, but that function never got called whereas when I engage the keyboard, the keyboardWillShow and keyboardWillHide functions are called. Can someone explain what's going on?

回答1:

Alright, so I figured out a solution. I needed to post the notification in the textViewDidChange function. I did that using this:

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

Then I recognized the notification in my viewDidLoad function with this:

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

Then I made this function under my viewDidLoad function:

func keyPressed(sender: NSNotification) {

}