gpt4 book ai didi

ios - 在 UICollectionView 中显示图像 - 如何实现图像之间的固定垂直间距?

转载 作者:技术小花猫 更新时间:2023-10-29 11:02:24 24 4
gpt4 key购买 nike

我正在使用 UICollectionView 在 iPhone 应用程序 (iOS6) 中呈现图像网格。

我正在为 UICollectionView 使用垂直滚动,所有图像都具有固定宽度和可变高度。设置图像的宽度,以便在 iPhone 上显示 3 列图像。这工作正常,我得到了在 GridView 中显示的图像。

但是,由于我的图像具有不同的高度,因此一列中图像之间的垂直间距会发生变化,这看起来不太好,如下图(用 HTML 制作的模型)所示:

Image showing how the images are currently laid out

相反,我想实现更流畅的流动,其中一列中图像之间的垂直间距相同。以下模型展示了我希望它如何工作:

Example of how I would like the flow of images to work

有什么解决办法吗?

此外,作为奖励问题,如果应用程序不是为 iOS6 构建的(因为 UICollectionView 仅在 iOS6 中可用),是否有人知道解决相同问题的方法。通过使用第 3 方组件或通过标准 iOS 控件解决它。

最佳答案

子类 UICollectionViewFlowLayout 并在该类中添加这些方法。 (请注意,这假设是垂直方向,它会跳过第一行,并且它们之间的间隔为 10 个像素。如果您需要水平版本,请参阅:how do you determine spacing between cells in UICollectionView flowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray* arr = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes* atts in arr) {
if (nil == atts.representedElementKind) {
NSIndexPath* ip = atts.indexPath;
atts.frame = [self layoutAttributesForItemAtIndexPath:ip].frame;
}
}
return arr;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes* atts =
[super layoutAttributesForItemAtIndexPath:indexPath];

if (indexPath.item == 0 || indexPath.item == 1) // degenerate case 1, first item of section
return atts;

NSIndexPath* ipPrev =
[NSIndexPath indexPathForItem:indexPath.item-2 inSection:indexPath.section];

CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
CGFloat rightPrev = fPrev.origin.y + fPrev.size.height + 10;
if (atts.frame.origin.y <= rightPrev) // degenerate case 2, first item of line
return atts;

CGRect f = atts.frame;
f.origin.y = rightPrev;
atts.frame = f;
return atts;
}

关于ios - 在 UICollectionView 中显示图像 - 如何实现图像之间的固定垂直间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com