systemLayoutSizeFittingSize: 和尺寸类的意外行为

Posted

技术标签:

【中文标题】systemLayoutSizeFittingSize: 和尺寸类的意外行为【英文标题】:Unexpected behavior of systemLayoutSizeFittingSize: and size classes 【发布时间】:2015-05-19 08:05:02 【问题描述】:

我遇到了一些与动态大小的单元格、自动布局和大小类有关的奇怪问题。我的测试项目完全基于 Ray 的教程。似乎唯一的区别是 UILabel 的大小类的字体大小。 当我在某个大小类中为标签设置另一个字体大小时,高度计算是错误的。我做了截图来说明它。

单元格的高度计算错误:

使用正确的单元格高度计算:

另外,我已经将test project推送到了github。

已编辑:

ViewController.m

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
  return [self heightForCellAtIndexPath:indexPath];

- (CGFloat)heightForCellAtIndexPath:(NSIndexPath *)indexPath 
  static CustomTableViewCell *sizingCell = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^
    sizingCell = [self.tableView dequeueReusableCellWithIdentifier:kBasicCell];
  );
  [self configurateCell:sizingCell atIndexPath:indexPath];
  return [self calculateHeightForCell:sizingCell];


- (CGFloat)calculateHeightForCell:(CustomTableViewCell *)cell 
  cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.frame), CGRectGetHeight(cell.bounds));

  [cell setNeedsLayout];
  [cell layoutIfNeeded];

  CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
  return size.height +1.0f;
 

CustomLabel.m

- (void)setBounds:(CGRect)bounds 
  [super setBounds:bounds];

  if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) 
    self.preferredMaxLayoutWidth = self.bounds.size.width;
    [self setNeedsUpdateConstraints];
  

【问题讨论】:

仅供参考:给定的 Web 链接在我的国家/地区已被阻止。 在此处粘贴代码部分和图片,而不是链接和链接说明。 @refdev 感谢您的建议。我已经编辑了我的问题(添加代码部分)。不幸的是,由于 *** 的信誉系统,我无法直接粘贴图像。 @refdev 感谢编辑! 【参考方案1】:

由于您已经在使用自动布局,我建议您也利用自调整单元格。您不需要任何行高计算,因为 ios 可以根据 UILabel 高度自动调整单元格的高度。

    将自动布局约束添加到您的 contentView 的 UILabel。这将导致单元格根据标签的内容调整其contentView 高度。 启用行高估计。

    self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 44.0;

有关详细信息,请参阅smileyborg 在其answer 中的详细演练,以在 UITableView 中使用自动布局实现动态单元格布局和可变行高

【讨论】:

感谢您的回复。据我所知,这种方法只能在 iOS 8 中使用

以上是关于systemLayoutSizeFittingSize: 和尺寸类的意外行为的主要内容,如果未能解决你的问题,请参考以下文章