在静态表格视图中动态调整文本视图和表格视图单元格的大小 [英] Resize text view and table view cell dynamically in static table view
问题描述
我有一个静态表视图,我将它用作我的应用程序的数据条目.其中一个单元格中有一个 UITextView ,它需要随着用户键入而动态地增长和收缩,以及单元格随着它的逻辑增长/收缩.我阅读了很多关于此的帖子,但我认为我被抛出了,因为我使用的是 STATIC 表视图.
I have a static table view that I am using as a sot of data entry for my app. One of those cells has a UITextView in it, which needs to grow and shrink dynamically as the user types, as well as the cell growing/shrinking logically with it. I read a bunch of posts on this but I think I am getting thrown because I am using a STATIC table view.
这是我调整大小的尝试(几乎完全失败):
Here is my resizing attempt (its pretty much a total fail):
- (void)textViewDidChange:(UITextView *)textView
{
self.numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;
float height = 44.0;
height += (textView.font.lineHeight * (self.numberOfLines - 1));
CGRect textViewFrame = [textView frame];
textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
[textView setFrame:textViewFrame];
[self.tableView beginUpdates];
[self.tableView endUpdates];
[self.messageTextView setContentInset:UIEdgeInsetsZero];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float height = 44.0;
if (self.messageTextView) {
height += (self.messageTextView.font.lineHeight * (self.numberOfLines - 1));
}
return height;
}
我会接受任何提示!谢谢.
I'll take any tips! Thanks.
推荐答案
您无需执行任何操作,只需通过以下代码:-有一个新的函数来代替 sizeWithFont,它是 boundingRectWithSize.
You don't have to do anything just go through this code:- There is a new function to replace sizeWithFont, which is boundingRectWithSize.
在我的项目中添加如下函数,使用iOS7上的新函数,iOS 7以下的旧函数,语法与sizeWithFont基本相同:
-(CGSize)text:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size{
if(IOS_NEWER_OR_EQUAL_TO_7){
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
nil];
CGRect frame = [text boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:attributesDictionary
context:nil];
return frame.size;
}else{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [text sizeWithFont:font constrainedToSize:size];
#pragma clang diagnostic pop
}
}
您可以将 IOS_NEWER_OR_EQUAL_TO_7 添加到您项目中的 prefix.pch 文件中:
#define IOS_NEWER_OR_EQUAL_TO_7 ( [ [ [ UIDevice currentDevice ] systemVersion ] floatValue ] >= 7.0 )
我从这个链接提到:-
iOS 7 中具有 UITextView 高度的 UITableViewCell?
这篇关于在静态表格视图中动态调整文本视图和表格视图单元格的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!