TextView是我们常见的文本编辑框,在使用的时候很多人把他当做texfield使用,这是错误的,以下是textcview的使用,包括协议:在开头声明<UITextViewDelegate>
// 初始化
text1 = [[UITextViewalloc]initWithFrame:CGRectMake(0,20, _vv2.frame.size.width,150)];
text1.delegate =self;
text1.textColor = [UIColorwhiteColor];
text1.backgroundColor = [UIColorblackColor];
text1.font = [UIFontsystemFontOfSize:16];
// 用协议限制字数
- (BOOL)textView:(UITextView *)atextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (range.location >50) {
returnNO;
}else
{
returnYES;
}
}
// textview的触发事件
-(void)textViewDidChange:(UITextView *)textView
{
NSInteger a;
a = 50 - textView.text.length;
if (a >=0) {
NSString * str = [NSStringstringWithFormat:@"还可以输入%ld字",a];
count.text = str;
}else
{
count.text =@"字数已满";
}
if (text1.text.length ==0) {
lable.text =@"请输入您的宝贵意见";
}else{
lable.text =@"";
}
NSLog(@"%ld",text1.text.length);
}
// 两个lable放在textview里面
lable = [[UILabelalloc]initWithFrame:CGRectMake(0,5, 100,20)];
lable.text =@"请输入内容";
lable.textColor = [UIColorlightGrayColor];
lable.font = [UIFontsystemFontOfSize:16];
count = [[UILabelalloc]initWithFrame:CGRectMake(0,text1.frame.size.height -20, text1.frame.size.width - 100, 20)];
count.text =@"还可以输入50字";
count.textColor = [UIColorlightGrayColor];
count.font = [UIFontsystemFontOfSize:16];
以下是效果图: