UICollectionView 垂直居中 [英] UICollectionView vertically Centred

查看:58
本文介绍了UICollectionView 垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为 (320,500) 的 UICollectionView 对象.

I have a UICollectionView object of size (320,500).

我需要以内容垂直居中的方式创建 UICollectionView.意味着如果内容的总大小是 (100,100),那么单元格应该在一个矩形 (0,200):(320,300) 中绘制自己.即 250 处垂直中心上方 50 处和下方 50 处.

I need a to create the UICollectionView in such a way that contents are vertically centred. Means if total size of the content is (100,100) then the cells should drawing itself in a rect (0,200):(320,300). that is 50 above and 50 below the vertical centre at 250.

问题是单元的数量和单元的大小仅在运行时决定.例如,如果单元格中的文本可以是 1 行,则大小为 ~ (100,50) .如果是 4 行大小将是 ~ (100,200).所以只有在我为最后一个单元格运行 collectionView:sizeForItemAtIndexPath: 之后,我才能确定第一个单元格的起始位置.

Problem is The number of cells and size of cells is decided only at runtime. For example if the text with in the cell can be 1 line is of size ~ (100,50) . If it is 4 lines size will be ~ (100,200). So it is only after I have run collectionView:sizeForItemAtIndexPath: for the last cell that I can determine what should be starting position for first cell.

我应该如何解决这个问题的任何开始建议.即使我将 Flowlayout 子类化,我如何在绘制最后一个单元格之前知道第一个单元格的位置?

Any starting suggestion how I should approach this problem. Even if I subclass Flowlayout how will I know the position of the first cell before I draw the last one ?

推荐答案

我是如何通过获取集合视图中最后一个元素的布局属性,然后决定视图的 contentInsets 的.它的问题是插图的变化并不平滑,因为没有动画,但其他方面它是有效的.

How I did it was by fetching the layout attributes of the last element in collection view and then deciding the contentInsets for the view. The problem it has is that the change in inset is not smooth since there is no animation but other wise it works.

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {

  NSArray* array = [super layoutAttributesForElementsInRect:rect];

    UICollectionViewLayoutAttributes* att = [array lastObject];
    if (att){
        CGFloat lastY = att.frame.origin.y + att.frame.size.height;
        CGFloat diff = self.collectionView.frame.size.height - lastY;

        if (diff > 0){
            UIEdgeInsets contentInsets = UIEdgeInsetsMake(diff/2, 0.0, 0.0, 0.0);
            self.collectionView.contentInset = contentInsets;
        }
    }
    return array;
}

这篇关于UICollectionView 垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆