UITextView UITextViewTextDidChangeNotification not being called on programmatic change of the text

五迷三道 提交于 2021-02-08 03:38:30

问题


I call this in the init of a custom UITextView:

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textChanged:)
                                                 name:UITextViewTextDidChangeNotification
                                               object:self];

The method textChangedis not called when I programmatically set textView.text = @""

Any Ideas on what I am doing wrong?


回答1:


Your shouldn't pass self to the last parameter, this parameter is notificationSender, it means that you just want to observer the notifications sent by self.

Observer like this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(textChanged:)
                                      name:UITextViewTextDidChangeNotification
                                      object:nil];

Hope it can help.




回答2:


The delegate pattern @Prince mentioned works as follows. Within your custom UITextView initialization:

[self setDelegate:self];

Then implement the appropriate delegate method:

#pragma - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    // Move the body of textChanged here
    // ...
}

This is a preferred way to manage responding to changes in an intimate/1:1 relationship, as outlined in this excellent post.




回答3:


extension UITextView {

func centerVertically() {
    let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
    let size = sizeThatFits(fittingSize)
    let topOffset = (bounds.size.height - size.height * zoomScale) / 2
    let positiveTopOffset = max(1, topOffset)
    contentOffset.y = -positiveTopOffset
}

}

//To update the text on editing use below code.

  func textViewDidChange(_ textView: UITextView) {
    textView.centerVertically()
}


来源:https://stackoverflow.com/questions/29631012/uitextview-uitextviewtextdidchangenotification-not-being-called-on-programmatic

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