iOStextView的代理方法展示

UITextView的代理方法

  1. 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的背景色设置为绿色.

  1. 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:让背景色返回最初的颜色。

  1. 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个字符了。

  1. textViewDidChangeSelection: 

在之前的方法中加入以下代码:

- (void)textViewDidChangeSelection:(UITextView *)textView{  

    NSLog(@"textViewDidChangeSelection:");  

只有当用户修改了text view中的内容时,textViewDidChange:方法才会被调用。在该方法中,可以对用户修改了text view中 的内容进行验证,以满足自己的一些实际需求。例如,这里有一个应用场景:当text view限制最多可以输入140个字符时,此时,在用户修改文本内容 时,你希望显示出还可以输入多少个字符。那么每次文本内容被用户修改的时候,更新并显示一下剩余可输入的字符个数即可。

  1. textViewDidChangeSelection: 

在之前的方法中加入以下代码:

- (void)textViewDidChangeSelection:(UITextView *)textView{ 

    NSLog(@"textViewDidChangeSelection:"); 

当用户选择text view中的部分内容,或者更改文本选择的范围,或者在text view中粘贴入文本时,函数textViewDidChangeSelection:将会被调用。该方法一般不使用,不过在某些情况下,非常有用。

原文地址:https://www.cnblogs.com/sunfuyou/p/6182611.html