Swift NSNotificationCenter? [英] Swift NSNotificationCenter?
问题描述
我正在尝试使UITextViewTextDidChangeNotification起作用.我是使用NSNotificationCenter的新手,所以我很难理解确切的情况.我在情节提要中有一个UITextView,并在ViewController类中为其创建了一个IBOutlet,并将其命名为textView.
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.
这是我的viewDidLoad函数:
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);
}
键盘通知效果很好.据我了解,它们调用与选择器同名的函数.那是对的吗?还是这里还有其他事情?我制作了一个名为keyPressed的函数,该函数将NSNotification作为参数,但是从未调用该函数,而当我使用键盘时,会调用keyboardWillShow和keyboardWillHide函数.有人可以解释发生了什么事吗?
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?
推荐答案
好的,所以我想出了一个解决方案.我需要在textViewDidChange函数中发布通知.我是这样做的:
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)
然后我通过以下方法在viewDidLoad函数中识别了通知:
Then I recognized the notification in my viewDidLoad function with this:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyPressed:"), name:"keyPressed", object: nil);
然后我在viewDidLoad函数下创建了此函数:
Then I made this function under my viewDidLoad function:
func keyPressed(sender: NSNotification) {
}
这篇关于Swift NSNotificationCenter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!