问题
I call this in the init of a custom UITextView:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textChanged:)
name:UITextViewTextDidChangeNotification
object:self];
The method textChanged
is 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