我有一个 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 的宽度是多少,大小计算都是一样的。
当从纵向旋转到横向时,这会导致单元格过大,而从横向旋转到纵向时会导致单元格过小。