-->

显示图像在UICollectionView - 如何实现图像之间固定垂直间距?(Display i

2019-07-18 14:29发布

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

我使用垂直滚动的UICollectionView,并且图像的所有具有固定的宽度和变化的高度。 图像的宽度如此设置,从而在iPhone上时,它显示的图像的3列。 该工程确定,我也得到在网格视图中显示的图像。

然而,由于我的图片有不同的高度,在一列图像之间的垂直距离而变化,这看起来不是很好,因为你可以在下面的图片中看到(在HTML做出了样机):

我反而希望实现多个流体流动,其中在一列中的图像之间的垂直间距是相同的。 下面的样机展示我怎么想它的工作:

的任何想法如何解决这个问题?

此外,作为奖金的问题,没有人知道一个方法来解决同样的问题,如果应用程序没有为iOS6的建(因为UICollectionView只适用于iOS6的)。 或者通过使用第三方组件或通过与标准iOS控制解决它。

Answer 1:

子类UICollectionViewFlowLayout和在类中添加这些方法。 (请注意,此处于垂直方向,它跳过第一行,这是他们之间的恒定10个像素见: 你如何确定单元格间距在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;
}


Answer 2:

对于斯威夫特3对于我这个代码工作,包括第一线的空间,顶部...

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    let arr = super.layoutAttributesForElements(in: rect)

    for atts:UICollectionViewLayoutAttributes in arr! {
        if nil == atts.representedElementKind {
            let ip = atts.indexPath
            atts.frame = (self.layoutAttributesForItem(at: ip)?.frame)!
        }
    }
    return arr
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let atts = super.layoutAttributesForItem(at: indexPath)

    if indexPath.item == 0 || indexPath.item == 1 {
        var frame = atts?.frame;
        frame?.origin.y = sectionInset.top;
        atts?.frame = frame!;
        return atts
    }

    let ipPrev = IndexPath(item: indexPath.item - 2, section: indexPath.section)

    let fPrev = self.layoutAttributesForItem(at: ipPrev)?.frame

    let rightPrev = (fPrev?.origin.y)! + (fPrev?.size.height)! + 10

    if (atts?.frame.origin.y)! <= rightPrev {
        return atts
    }

    var f = atts?.frame
    f?.origin.y = rightPrev
    atts?.frame = f!
    return atts
}


文章来源: Display images in a UICollectionView - how to achieve fixed vertical spacing between images?