{
float heightText;//文字高度
}
NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:20.0]};
CGSize contentSize=[@"我" sizeWithAttributes:dict];
heightText=contentSize.height;
实现 UITextViewDelegate 协议的
-(void)textViewDidChange:(UITextView *)textView
{
float currentLineNum=1;//默认文本框显示一行文字
float textViewWidth=self.textView.frame.size.width;//取得文本框高度
NSString *content=textView.text;
NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:20.0]};
CGSize contentSize=[content sizeWithAttributes:dict];//计算文字长度
float numLine=ceilf(contentSize.width/textViewWidth); //计算当前文字长度对应的行数 if(numLine>currentLineNum )
{ //如果发现当前文字长度对应的行数超过。 文本框高度,则先调整当前view的高度和位置,然后调整输入框的高度,最后修改currentLineNum的值
self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y-heightText*(numLine-currentLineNum);
self.frame.size.width, self.frame.size.height+heightText*(numLine-currentLineNum));
textView.frame=CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, textView.frame.size.height+heightText*(numLine-currentLineNum));
currentLineNum=numLine;
}else if (numLine<currentLineNum ){
//次数为删除的时候检测文字行数减少的时候
self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y+heightText*(currentLineNum-numLine);
self.frame.size.width, self.frame.size.height-heightText*(currentLineNum-numLine));
textView.frame=CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, textView.frame.size.height-heightText*(currentLineNum-numLine));
currentLineNum=numLine;
}
}