首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift NSNotificationCenter?

Swift NSNotificationCenter?
EN

Stack Overflow用户
提问于 2015-02-02 06:10:59
回答 1查看 4.1K关注 0票数 0

我在试着让UITextViewTextDidChangeNotification正常工作。我刚开始使用NSNotificationCenter,所以我很难理解到底是怎么回事。我在故事板中有一个UITextView,并且在我的ViewController类中为它创建了一个IBOutlet,并将其命名为textView。

这是我的viewDidLoad函数:

代码语言:javascript
复制
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函数都会被调用。有人能解释一下发生了什么事吗?

EN

回答 1

Stack Overflow用户

发布于 2015-02-02 07:31:36

好吧,所以我想出了一个解决方案。我需要在textViewDidChange函数中发布通知。我是这样做的:

代码语言:javascript
复制
NSNotificationCenter.defaultCenter().postNotificationName("keyPressed", object: nil)

然后,我在我的viewDidLoad函数中识别了通知,如下所示:

代码语言:javascript
复制
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyPressed:"), name:"keyPressed", object: nil);

然后我在我的viewDidLoad函数下创建了这个函数:

代码语言:javascript
复制
func keyPressed(sender: NSNotification) {

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28268524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档