的UITableViewCell高度自动布局
问题描述:
我有以下的UITableViewCell布局,我使用的自动布局处理这个的UITableViewCell高度自动布局
=========
| Image | Name Label
| | Short description Label
=========
Description Label
这里描述标签是可选的,它会根据内容隐藏/显示,我使用的计算上heightForRowAtIndexPath
细胞的高度
- (CGFloat)heightForTableView:(UITableView *)tableView cell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.bounds = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGSize cellSize = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
// Add extra padding
CGFloat height = cellSize.height;// + 1;
return height;
}
即使我隐藏隐藏描述标签它返回相同高度的单元格,我失踪了什么?
任何人都可以建议最好的方式来处理这种情况与自动布局?
编辑1:设置空作品,但有没有更好的方法?
答
heightForRowAtIndexPath也针对所有行调用。因此,对于您正在隐藏描述标签的行,对于同一行,您将cat设置为heightForRowAtIndexPath方法中的高度。
例如。 第4行您想通过检查某些条件来隐藏描述标签。
than heightForRowAtIndexPath您可以检查同一行的相同条件,并且可以返回所需的高度,而不显示说明标签。
比方说,
if(description.length==0)
{
return 100;// description label hidden
}
else
{
return 140;// description label shown
}
答
我建议计算每个细胞如下的高度。通过查看你的问题,我假设所有的单元格应该有相同的高度,如果没有描述标签,是正确的?让我们假设它是60.所以,你需要做的是根据它的描述文本计算每个单元格的高度,并将其添加到没有描述文本的单元格的高度。这在你的heightForTableView
代表中会是这样的。
- (CGFloat)heightForTableView:(UITableView *)tableView cell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
int cellWidth = 320; // assuming it is 320
int constantHeight = 60;
NSString * str = [[yourarray objectAtIndex:indexPath.row] objectForKey:@"DescriptionKey"];
int height = [self calculateHeightForText:str withWidth:cellWidth andFont:[UIFont systemFontOfSize:16]];
// replace systemFontSize with your own font
return height + constantHeight;
}
// Depreciated in iOS7
- (int)calculateHeightForText:(NSString *)string withWidth:(int)width andFont:(UIFont *)font
{
CGSize textSize = [string sizeWithFont:font constrainedToSize:CGSizeMake(width, 20000) lineBreakMode: NSLineBreakByWordWrapping];
return ceil(textSize.height);
}
// Introduced in iOS7
- (int)calculateHeightForText:(NSString *)string withWidth:(int)width andFont:(UIFont *)font
{
int maxHeightForDescr = 1000;
NSDictionary *attributes = @{NSFontAttributeName: font};
CGRect rect = [string boundingRectWithSize:CGSizeMake(width, maxHeightForDescr)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
return rect.size.height;
}
我已经写了两种方法calculateHeightForText,一种是在贬值和iOS7工程都iOS6的少和iOS7但:第二个建议方法iOS7但不会为iOS7工作。如果您发现一些令人困惑的事情,请告诉我,或者需要进一步的帮助。会很乐意进一步帮助。
可以显示计算细胞高度的完整代码吗? – 2014-11-06 05:24:20
你在哪里隐藏标签?在这个方法被调用之前? – 2014-11-06 05:34:26
是的,当配置它与模型 – Abhishek 2014-11-06 05:35:15