0

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?

tdon
  • 1,421
  • 15
  • 24
  • Are you sure that the if statement is actually executed? I'd put a println("Working") or something in there, just to be sure. – vegather Feb 01 '15 at 23:07
  • I've debugged it and I know it's being executed. I figured it out though. I needed to post the notification... – tdon Feb 01 '15 at 23:09
  • What, exactly, is the problem you are having? Also, remove your edit of a solution. If you found a solution, then add it as an Answer and accept your answer. That's how Stack Overflow works. – jww Feb 01 '15 at 23:20

1 Answers1

0

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) {

}
tdon
  • 1,421
  • 15
  • 24
  • 1
    or you can do it in deinit. http://natashatherobot.com/ios8-where-to-remove-observer-for-nsnotification-in-swift/ – Sinisa Drpa Feb 02 '15 at 01:34
  • Generally, you want to put these in viewWillAppear and viewDidDisappear. That way you receive the notifications only when you need them. – vegather Feb 02 '15 at 11:51