【发布时间】:2015-01-14 15:49:36
【问题描述】:
我有一个 UITableViewCell,其 UIImage 固定在左上角,标签位于其右侧:
-(UITableViewCell*) adCellFromTableView:(UITableView*)tableView
{
//Build the text
NSString* adText = NSLocalizedString(@"MyFamily_fremiumAd", nil);
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:adText];
NSUInteger newLineLocation = [adText rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location;
//Set the first line in orange
NSDictionary* firstLineAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],
NSForegroundColorAttributeName:ORANGE};
[attrString addAttributes:firstLineAttributes range:NSMakeRange(0, newLineLocation)];
//Set other lines in white
NSDictionary* otherLinesAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:11],
NSForegroundColorAttributeName:[UIColor whiteColor]};
[attrString addAttributes:otherLinesAttributes range:NSMakeRange(newLineLocation, adText.length - newLineLocation)];
//Get the cell
if (!adCell)
{
adCell = [tableUsers dequeueReusableCellWithIdentifier:@"fremiumAd"];
}
//Set the text
UILabel* label = (UILabel*)[adCell viewWithTag:1];
label.attributedText = attrString;
//Hide the separator
adCell.separatorInset = UIEdgeInsetsMake(0, adCell.bounds.size.width, 0, 0);
return adCell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [self adCellFromTableView:tableView];
//Make sure the cell's bounds are the same as tableview's before calculating the height
//This is important when we calculate height after a UI rotation.
cell.bounds = CGRectMake(0, 0, tableView.bounds.size.width, 0);
NSLog(@"cell.bounds: %@",NSStringFromCGRect(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGSize fittingSize = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
NSLog(@"fittingSize: %@",NSStringFromCGSize(fittingSize));
return fittingSize.height;
}
当我在 iOS 7.1 模拟器上运行应用时,systemLayoutSizeFittingSize 总是返回 0:
cell.bounds: {{0, 0}, {320, 0}}
拟合尺寸:{0,0}
当我在 iOS 8.1 模拟器上运行应用程序时,systemLayoutSizeFittingSize 返回正确的值:
cell.bounds: {{0, 0}, {320, 0}}
拟合尺寸:{320, 154.5}
我错过了什么?
编辑:
我使用[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 而不是[cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 解决了这个问题
但这只是解决了一半:当我在单元格可见的情况下旋转时,大小计算就可以了。但是当我将单元格滚动出屏幕,旋转 UI,然后滚动回单元格时,iOS 7.1 中的高度计算再次错误
以下是从横向旋转到纵向之前的日志:
tableView 边界:{{0, 0}, {569, 227}}
cell.bounds : {{0, 0}, {569,0}}
cell.contentView: {{0, 0}, {569, 0}}
拟合尺寸:{559, 162}
以下是从横向旋转到纵向后的日志:
tableView 边界:{{0, 249}, {321, 463}}
cell.bounds : {{0, 0}, {321,0}}
cell.contentView: {{0, 0}, {321, 0}}
拟合尺寸:{559, 162}
如你所见,无论cell/cell.contentView的宽度是多少,大小计算都是一样的。
这会导致从纵向旋转到横向时单元格过大,而从横向旋转到纵向时会导致单元格过小。
【问题讨论】:
-
最后通过在 didRotateFromInterfaceOrientation 中重新加载表格来修复它:但我仍在寻找无需重新加载表格的工作。
标签: ios uitableview autolayout ios7.1 ios8.1