【问题标题】:Resize / scale content of UICollectionView cell within layout transition在布局转换中调整 UICollectionView 单元格的大小/缩放内容
【发布时间】:2014-03-25 07:08:42
【问题描述】:

我正在处理来自https://github.com/hebertialmeida/HAPaperViewControllerhttps://github.com/wtmoose/TLLayoutTransitioning 的示例项目的 CollectionViewLayout 的转换,但不知道如何在小布局和大布局之间自动调整单元格的内容。

例如我在 CollectionViewCell 中有一个 UILabel,它应该是定义(固定)位置的单元格宽度的一半。完成向大布局的过渡后,标签也应为单元格的一半(相对位置相同),但字体更大(或调整大小)。

在这里使用自动布局还是使用 CGAffineTransformMakeScale 缩放 contentView?

【问题讨论】:

  • 对不起,我刚看到这个。我在 GitGHub 上发布了答案和示例代码

标签: ios ios7 uicollectionview uicollectionviewcell uicollectionviewlayout


【解决方案1】:

我更新了TLLayoutTransitioning 中的“调整大小”示例项目,以演示如何做到这一点。

该方法涉及使用 TLLayoutTransitioning 回调之一在过渡的每一步更新字体大小。您可能不想使用仿射变换,因为您会在大尺寸下得到模糊的缩放文本。

第一步是定义一个方法来设置标签的字体大小。你可以使用任何你喜欢的公式,但我已经使字体比例与单元格的宽度成比例:

- (void)updateLabelScale:(UILabel *)label cellSize:(CGSize)cellSize
{
    CGFloat pointSize = cellSize.width * 17 / 128.f;
    label.font = [UIFont fontWithName:label.font.fontName size:pointSize];
}

您需要在cellForItemAtIndexPath 中调用此方法,以确保屏幕上出现的新标签正确缩放:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [super collectionView:collectionView cellForItemAtIndexPath:indexPath];
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    ...
    [self updateLabelScale:label cellSize:cell.bounds.size];
    return cell;
}

标签的中心被限制在单元格的中心,大小由intrinsicContentSize 决定。因此,当您更改字体时,标签的大小会自动调整以适应。

最后,您将使用updateLayoutAttributes 回调根据新的布局属性更新可见单元格的字体大小(您无需担心不可见的单元格,因为您正在处理cellForRowAtIndexPath):

__weak ResizeCollectionViewController *weakSelf = self;
[layout setUpdateLayoutAttributes:^UICollectionViewLayoutAttributes *(UICollectionViewLayoutAttributes *pose, UICollectionViewLayoutAttributes *fromPose, UICollectionViewLayoutAttributes *toPose, CGFloat progress) {
    CGSize cellSize = pose.bounds.size;
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:pose.indexPath];
    if (cell) {
        UILabel *label = (UILabel *)[cell viewWithTag:1];
        [weakSelf updateLabelScale:label cellSize:cellSize];
    }
    return nil;
}];

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多