在iOS应用程序中动态调整表单元格大小
我正在尝试使用在iOS应用程序中动态调整表单元格大小,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我正在尝试使用XCode 4.2创建一个Twitter客户端。(iOS版本5)我希望我的应用程序的主时间线与Twitter iOS应用程序的时间线相似: 我使用的是一个带有一个标签和三个按钮的原型单元格的UITableView。下面是我用来设置高度的代码: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
XCode 4.2
创建一个Twitter客户端。(iOS版本5
)我希望我的应用程序的主时间线与Twitter iOS应用程序的时间线相似:
我使用的是一个带有一个标签和三个按钮的原型单元格的UITableView
。下面是我用来设置高度的代码:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = @"TweetContainerCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
@try {
UILabel* tweetLabel;
if(cell != nil) {
tweetLabel = (UILabel*)[cell.contentView viewWithTag:1];
NSString* tweetText = tweetLabel.text;
CGSize expectedLabelSize = [tweetText sizeWithFont:[UIFont fontWithName:tweetLabel.font.fontName size:20] constrainedToSize:CGSizeMake(CGFLOAT_MIN, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
//[tweetLabel setFrame:CGRectMake(tweetLabel.frame.origin.x, tweetLabel.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)];
//[cell.textLabel setFrame:tweetLabel.bounds];
//[tweetLabel sizeToFit];
//[cell setFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)];
//[cell sizeToFit];
NSLog(@"Font size: %f", expectedLabelSize.height);
return (expectedLabelSize.height * 2);
}
}
/* Imgur URL: http://i.imgur.com/lHnsAsP.png */
/* http://i.imgur.com/hA9EKfI.png */
@catch (NSException* exception) {
NSLog(@"Exception: %@", exception);
}
return 0;
}
然而,这就是我的应用程序最终的样子:
问题是:
1) 每个单元格似乎与整张桌子上最高的单元格具有相同的高度,而不是具有不同的高度
2) 因此,每个单元格的上边框和文本之间的空间不同(因为iOS
将文本垂直居中)
我正在学习iOS开发,即使在做了大量的研究和花费了大量的时间之后,也不能做这么简单的事情,这似乎真的令人沮丧。非常感谢您的帮助
(如果我提供的信息不够,这里是包含整个项目的ZIP文件:)您的问题是您的标签尚未创建,因为
tableView:heightforrowatinexpath:
最初是在创建单元格的tableView:cellforrowatinexpath:
之前调用的。在tableView:heightForRowAtIndexPath:
中,应尽可能有效地确定单元格的高度,而不涉及UIView
要实现这一点,您应该将NSString
存储在表视图数据源的其他位置,并基于此计算expectedLabelSize
另外请注意,IOS 7中不推荐使用sizeWithFont:
,因此对于IOS 7及更高版本,您应该使用sizeWithAttributes: