Specifying one Dimension of Cells in UICollectionView using Auto Layout

前端 未结 5 1655
执念已碎
执念已碎 2020-11-30 16:01

In iOS 8 the UICollectionViewFlowLayout supports automatically resizing cells based on their own content size. This resizes the cells in both width and height a

5条回答
  •  有刺的猬
    2020-11-30 16:41

    Try fixing your width in the preferred layout attributes:

    - (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
        UICollectionViewLayoutAttributes *attributes = [[super preferredLayoutAttributesFittingAttributes:layoutAttributes] copy];
        CGSize newSize = [self systemLayoutSizeFittingSize:CGSizeMake(FIXED_WIDTH,layoutAttributes.size) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
        CGRect newFrame = attr.frame;
        newFrame.size.height = size.height;
        attr.frame = newFrame;
        return attr;
    }
    

    Naturally you also want to ensure that you setup your layout correctly to:

    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *) self.collectionView.collectionViewLayout;
    flowLayout.estimatedItemSize = CGSizeMake(FIXED_WIDTH, estimatedHeight)];
    

    Heres something I put on Github that uses constant width cells and supports dynamic type so the height of the cells updates as the system font size changes.

提交回复
热议问题