<pre name="code" class="objc">
iOS开发中遇到要写textview的提示文字 写这些东西要用到textview的代理方法
下面有我和大家分享一下是如何实现的吧
1. 要创建一个UITextView 对象和一个Label对象
import "TextViewController.h" @interface TextViewController ()<UITextViewDelegate>//添加textview的代理 @property(nonatomic,strong) UITextView *textView; @property(nonatomic,strong) UILabel *promptTitle; @end
//后面代理方法会用到创建的对象 所以尽量创建一个全局的
self.textView = [[UITextView alloc]initWithFrame:CGRectMake(20, label.frame.size.height +10, 260, 110)]; self.textView.pagingEnabled = YES; self.textView.clipsToBounds = YES; self.textView.layer.borderWidth = 1; self.textView.tag = 100; self.textView.delegate = self;//将代理设置给本类 [self.view addSubview:self.textView]; //创建Label 加提示语 self.promptTitle = [[UILabel alloc]initWithFrame:CGRectMake(5,5,100,20)]; self.promptTitle.text = @"最多可输入140字"; self.promptTitle.font = [UIFont systemFontOfSize:12.0]; [self.promptTitle setTextColor:[UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:0.8]]; // [self.textView addSubview:self.promptTitle];
2.textView的代理方法
//判断是否超出最大限额 140 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if ([text isEqualToString:@""] && range.length > 0) { //删除字符肯定是安全的 return YES; } else { if (textView.text.length - range.length + text.length > 140) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大可输入长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];//如果输入的文字大于140 则提示 <span style="font-family: Arial, Helvetica, sans-serif;">"超出最大可输入长度" 并不能继续输入文字</span> [alert show]; return NO; } else { return YES; } } }
//点击屏幕任意一处取消键盘的第一响应项 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; }