原文:http://www.cnblogs.com/Peterahan/archive/2013/04/17/3026130.html
最近在做一个需求的时候,出现了这样一个问题:textViewDidChange当程序中给UITextView赋值的时候,是不被调用的,如官方文档对该方法的说明:
Tells the delegate that the text or attributes in the specified text view were changed by the user.
The text view calls this method in response to user-initiated changes to the text. This method is not called in response to programmatically initiated changes.
如果必要在程序中给UITextView赋值又希望有相应的动作的话,我采用了一个替代方案:
1.在合适的地方注册一个系统的通知(注意name,系统定义的):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChangedExt:) name:UITextViewTextDidChangeNotification object:nil];
2.实现textChangedExt:
- (void)textChangedExt:(NSNotification *)notification
{
//todo sth...
}
用下面这个代理方法也可以。。。
#pragma mark - UITextField Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string isEqualToString:@""]) {
return YES;
}
if ([[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""] length] >= 20) {
return NO;
}
return YES;
}