ios - 在布局转换中调整/缩放 UICollectionView 单元格的内容

标签 ios ios7 uicollectionview uicollectionviewcell uicollectionviewlayout

我正在研究来自 https://github.com/hebertialmeida/HAPaperViewController 的示例项目的 CollectionViewLayout 的转换。和 https://github.com/wtmoose/TLLayoutTransitioning并且无法弄清楚如何在小布局和大布局之间自动调整单元格内容的大小。

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

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

最佳答案

我已经在 TLLayoutTransitioning 中更新了“Resize”示例项目演示如何做到这一点。

该方法涉及使用 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;
}];

关于ios - 在布局转换中调整/缩放 UICollectionView 单元格的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627637/

相关文章:

objective-c - 在 NSObject 中构建后,UIButton 不会单击

ios - WebView 从照片库中选择文件

ios - 在ios 7中,UITableViewCell Accessory DetailDisclosureButton被分为两个不同的附属按钮

objective-c - UICollectionView 可滚动年 View : performance issue

ios - 如何在表格 View 中列出距离当前用户位置最近的用户 - iOS swift?

ios - 获取属性字符串的颜色变化词

ios - 如何更改/设置/管理 uicollectionview 中各部分之间的边框?

ios - 在 scrollToItemAtIndexPath 之后获取 UICollectionView 单元格位置

ios - 本地化以及如何在 iOS 应用程序上处理网络内容

javascript - iOS7 Safari 手机| Html 视频流 |未触发结束事件