UITextView的代理方法
- textViewShouldBeginEditing: and textViewDidBeginEditing:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
NSLog(@"textViewShouldBeginEditing:");
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
NSLog(@"textViewDidBeginEditing:");
textView.backgroundColor = [UIColor greenColor];
}
在text view獲得焦點之前會調用textViewShouldBeginEditing: 方法。當text view獲得焦點之后,並且已經是第 一響應者(first responder),那么會調用textViewDidBeginEditing: 方法。當text view獲得焦點時要想 做一些自己的處理,那么就在這里進行。在
我們的示例中,當text view獲得焦點時,是把text view的背景色設置為綠色.
- textViewShouldEndEditing: and textViewDidEndEditing:
在之前的方法中加入以下代碼
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
NSLog(@"textViewShouldEndEditing:");
textView.backgroundColor = [UIColor whiteColor];
return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
NSLog(@"textViewDidEndEditing:");
}
當text view失去焦點之前會調用textViewShouldEndEditing。在示例中,我們使用textViewShouldEndEditing:讓背景色返回最初的顏色。
- textView:shouldChangeCharactersInRange:replacementString
在之前的方法中加入以下代碼:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSCharacterSet *doneButtonCharacterSet = [NSCharacterSet newlineCharacterSet];
NSRange replacementTextRange = [text rangeOfCharacterFromSet:doneButtonCharacterSet];
NSUInteger location = replacementTextRange.location;
if (textView.text.length + text.length > 140){
if (location != NSNotFound){
[textView resignFirstResponder];
}
return NO;
} else if (location != NSNotFound){
[textView resignFirstResponder];
return NO;
}
return YES;
}
每次用戶通過鍵盤輸入字符時,在字符顯示在text view之 前,textView:shouldChangeCharactersInRange:replacementString方法會被調用。這個方法中可以 方便的定位測試用戶輸入的字符,並且限制用戶輸入特定的字符。在上面的代碼中,我使用done鍵來隱藏鍵盤:通過檢測看replacement文本中是否包含newLineCharacterSet任意的字符。
如果有一個字符是來自newLineCharacterSet的,那么說明done按鈕被按過了,因此應該將鍵盤隱藏起來。另外,在用戶每次輸入內容時,還 檢測text view當前文本內容的長度,如果大於140個字符,則返回NO,這樣text view就可以限制輸入140個字符了。
- textViewDidChangeSelection:
在之前的方法中加入以下代碼:
- (void)textViewDidChangeSelection:(UITextView *)textView{
NSLog(@"textViewDidChangeSelection:");
}
只有當用戶修改了text view中的內容時,textViewDidChange:方法才會被調用。在該方法中,可以對用戶修改了text view中 的內容進行驗證,以滿足自己的一些實際需求。例如,這里有一個應用場景:當text view限制最多可以輸入140個字符時,此時,在用戶修改文本內容 時,你希望顯示出還可以輸入多少個字符。那么每次文本內容被用戶修改的時候,更新並顯示一下剩余可輸入的字符個數即可。
- textViewDidChangeSelection:
在之前的方法中加入以下代碼:
- (void)textViewDidChangeSelection:(UITextView *)textView{
NSLog(@"textViewDidChangeSelection:");
}
當用戶選擇text view中的部分內容,或者更改文本選擇的范圍,或者在text view中粘貼入文本時,函數textViewDidChangeSelection:將會被調用。該方法一般不使用,不過在某些情況下,非常有用。