iOS 使用UITextView计算高度,一行代码搞定
2017-03-26 本文已影响960人
为之则易ing
看其它文章介绍的方法很多,一般都是计算高度,问题太多。其实没那么麻烦。
一行代码的事;
直接上代码:
-(void)textViewDidChange:(UITextView *)textView{
float textViewHeight = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)].height;
CGRect frame = textView.frame;
frame.size.height = textViewHeight;
textView.frame = frame;
}
是不是很简单!!!
当textView高度改变时,textview文字位置显示错误,错位显示,位置偏上
Paste_Image.png解决办法:
textView.scrollEnabled = NO;
当textView放在tableViewCell上,当textView高度改变时需要刷新tableView,
-(void)textViewDidChange:(UITextView *)textView{
float textViewHeight = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)].height;
if (textViewHeight != _cellHeight && textViewHeight > 50) {
_cellHeight = textViewHeight;
[_tableView reloadData];
}
}
此时存在一个问题,键盘会隐藏,解决方法:在tableView代理中重新设为第一响应
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestTableViewCell"];
cell.textV.delegate = self;
cell.textV.scrollEnabled = NO;
cell.textVH.constant = _cellHeight;
dispatch_async(dispatch_get_main_queue(), ^{//这行代码一定要加上
[cell.textV becomeFirstResponder];
});
return cell;
}