Swift NSNotificationCenter?

跟風遠走 提交于 2020-01-11 12:43:56

问题


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

}


来源:https://stackoverflow.com/questions/28268524/swift-nsnotificationcenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!