目錄
- 1 實現監(jiān)聽的三種方法
- 2 實現代理的兩種方法
實現監(jiān)聽的三種方法-

我們常常都會在項目當中遇到這樣的頁面,上個頁面輸入框是用TextView來做的,那么其實我們都會給它添加的文字進行限制,那么現在的問題來了。我們怎么限制它輸入的文字呢?有兩種方法。
- 我們用到了textView的監(jiān)聽方法-- 用command+這個控件你就會看到底層對于實現textView的三種監(jiān)聽方法--
UIKIT_EXTERN NSString * const UITextViewTextDidBeginEditingNotification;
UIKIT_EXTERN NSString * const UITextViewTextDidChangeNotification;
UIKIT_EXTERN NSString * const UITextViewTextDidEndEditingNotification;
這三種監(jiān)聽的方法分別是(1、開始編譯 2、編譯中 3、停止編譯(鍵盤收回時))
//開始編輯
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginediting:) name:UITextViewTextDidBeginEditingNotification object:self.textTextView];
//停止編輯
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endediting:) name:UITextViewTextDidEndEditingNotification object:self.textTextView];
/*改變*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doingEditing:) name:UITextViewTextDidChangeNotification object:self.textTextView];
然后需要實現這三種監(jiān)聽的實現方法--
#pragma mark 開始編譯
-(void)beginediting:(NSNotification *)notification
{
NSLog(@"開始編譯");
}
#pragma mark 停止編譯
-(void)endediting:(NSNotification *)notification
{
NSLog(@"停止編譯")
}
#pragma mark 正在編譯
-(void)doingEditing:(NSNotification *)notification
{
if (self.textTextView.text.length>=200) {
/*停止編輯*/
self.textTextView.editable = NO;
}
else{
self.textTextView.editable = YES;
}
}
不要忘記釋放監(jiān)聽
#pragma mark 釋放通知
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
備注:其實設置editable這個屬性并不是最智能的方法,因為設置editable為no停止編譯是讓textView鍵盤無法再次彈起,并且無法進行操作,所以這樣的方式并不是最智能的,那么什么是最智能的方式呢?如下---
代理的兩種方法-
#pragma mark UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString * nsTextContent=textView.text;
long existTextNum=[nsTextContent length];
self.textLabel.text=[NSString stringWithFormat:@"還可以輸入%ld字",200-existTextNum];
if (range.location>=200)
{
return NO;
}
else
{
return YES;
}
}
#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
//該判斷用于聯(lián)想輸入
if (textView.text.length >= 200)
{
textView.text = [textView.text substringToIndex:200];
}
}
備注:不要忘記寫代理方法<UITextViewDelegate>和self.textTextView.delegate = self ;
上面代碼中textView.text = [textView.text substringToIndex:200];的意思就是代表無論是復制過來的文字還是手動輸入的文字,只要到了200個就不會再讓文字繼續(xù)添加,但是如果不添加textView.text = [textView.text substringToIndex:200];這句話僅僅只能搞定手動輸入的文字,并不能防止復制過來的文字不超過200.
總結
以上方式都可以對textView和textField進行監(jiān)聽和限制文字添加。
本人個人微信公眾號地址(喜歡記得關注??)
