我在试着让UITextViewTextDidChangeNotification正常工作。我刚开始使用NSNotificationCenter,所以我很难理解到底是怎么回事。我在故事板中有一个UITextView,并且在我的ViewController类中为它创建了一个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);
}键盘通知效果很好。据我所知,它们调用一个与选择器同名的函数。对吗?或者这里还发生了什么呢?我创建了一个名为keyPressed的函数,该函数接受NSNotification作为参数,但该函数从未被调用过,而当我使用键盘时,keyboardWillShow和keyboardWillHide函数都会被调用。有人能解释一下发生了什么事吗?
发布于 2015-02-02 07:31:36
好吧,所以我想出了一个解决方案。我需要在textViewDidChange函数中发布通知。我是这样做的:
NSNotificationCenter.defaultCenter().postNotificationName("keyPressed", object: nil)然后,我在我的viewDidLoad函数中识别了通知,如下所示:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyPressed:"), name:"keyPressed", object: nil);然后我在我的viewDidLoad函数下创建了这个函数:
func keyPressed(sender: NSNotification) {
}https://stackoverflow.com/questions/28268524
复制相似问题