ios - UICollectionViewCell systemLayoutSizeFittingSize 返回不正确的宽度

标签 ios xcode6 autolayout uicollectionview

我一直在玩弄动态 UICollectionViewCell,并注意到在 iOS 8 上调用 cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)UICollectionViewCell 上返回不正确的宽度。目前解决此问题的唯一解决方法是显式添加宽度约束以强制单元格的宽度。以下代码用于 Cell 子类:

func calculatePreferredHeightForFrame(frame: CGRect) -> CGFloat {
    var newFrame = frame
    self.frame = newFrame
    let widthConstraint = NSLayoutConstraint(item: contentView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: CGRectGetWidth(frame))
    contentView.addConstraint(widthConstraint)
    self.setNeedsUpdateConstraints()
    self.updateConstraintsIfNeeded()
    self.setNeedsLayout()
    self.layoutIfNeeded()
    let desiredHeight: CGFloat = self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    newFrame.size.height = CGFloat(ceilf(Float(desiredHeight)))
    contentView.removeConstraint(widthConstraint)
    return CGRectGetHeight(newFrame)
}

我知道在 iOS 8 和动态 UICollectionViewFlowLayout 中,UICollectionViewCell 的 contentView 以不同方式处理约束,但是我在这里遗漏了什么吗?需要做什么才能确保 systemLayoutSizeFittingSize 在单元格上使用特定宽度?

我也看到了这篇文章 ( Specifying one Dimension of Cells in UICollectionView using Auto Layout ),我相信这实际上可能会使我的问题无效。也许 UICollectionViewFlowLayout 不是为只有一个动态维度的单元格设计的,但这仍然不能解释为什么单元格给出了不寻常的宽度。

最佳答案

我遇到过同样的问题。关键是在获取 systemLayoutSize 时使用优先级。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.prototypeCell) {
        self.prototypeCell = [TrainingMenuCell new];
        self.prototypeCell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    }

    [self configureCell:self.prototypeCell forIndexPath:indexPath];
    [self.prototypeCell setNeedsLayout];
    [self.prototypeCell layoutIfNeeded];

    CGFloat width = CGRectGetWidth(collectionView.frame) - 12;
    CGSize fittingSize = UILayoutFittingCompressedSize;
    fittingSize.width = width;

    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:fittingSize withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityDefaultLow];
    return size;
}

关于ios - UICollectionViewCell systemLayoutSizeFittingSize 返回不正确的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670951/

相关文章:

ios - Xcode 6 - 从命令行启动模拟器

ios - 缺少 XCTest 框架

ios - UIViewContentModeCenter 添加填充

ios - 基于 AutoLayout 的应用程序中的 NSAutoresizingMaskLayoutConstraint 错误

ios - 如何在横向模式下使用自动布局设置水平文本字段?

ios - 范围无效 :basic_info. 请改用 public_profile、user_friends

ios - 如何使用解析保持当前用户 session 处于事件状态?

javascript - 解析作业未按计划时间间隔运行

ios - 为类型化数组创建快速数组扩展

iphone - 是否有用于 CALayer HitTest 的 MouseChildren?