如何在UICollectionView中居中行? [英] How can I center rows in UICollectionView?

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

问题描述

我有一个带有随机单元格的 UICollectionView 。有没有什么方法可以让我居中行?

I have a UICollectionView with random cells. Is there any method that allows me to center rows?

这是默认情况下的样子:

This is how it looks by default:

[ x x x x x x ]  
[ x x x x x x ]  
[ x x         ]  

以下是所需的布局:

[ x x x x x ]  
[ x x x x x ]  
[    x x    ]  


推荐答案

首先有点背景 - a UICollectionView UICollectionViewLayout 结合使用,它决定了单元格在视图中的放置方式。这意味着集合视图非常灵活(您可以使用它创建几乎任何布局),但也意味着修改布局可能会有点混乱。

A bit of background first - a UICollectionView is combined with a UICollectionViewLayout which determines how the cells get placed in the view. This means a collection view is very flexible (you can create almost any layout with it), but also means modifying layouts can be a little confusing.

创建一个全新的布局class很复杂,所以你想尝试修改默认布局( UICollectionViewFlowLayout )以使你的中心对齐。为了使它更简单,你可能想要避免对流程布局本身进行子类化。

Creating an entirely new layout class is complex, so instead you want to try and modify the default layout (UICollectionViewFlowLayout) to get your center alignment. To make it even simpler, you probably want to avoid subclassing the flow layout itself.

这是一种方法(它可能不是最好的方法,但它是第一个我可以想到) - 将您的单元格分为两部分,如下所示:

Here's one approach (it may not be the best approach, but it's the first one I can think of) - split your cells into two sections, as follows:

[ x x x x x ] <-- Section 1 
[ x x x x x ] <-- Section 1 
[    x x    ] <-- Section 2 

如果你知道滚动视图的宽度和每行中可以容纳的单元格数,这应该是相当简单的。

This should be fairly straightforward, provided you know the width of your scroll view and the number of cells that can fit in each row.

然后,使用 collectionView:layout:insetForSectionAtIndex:委托方法,用于设置第二部分的边距,使其看起来垂直居中。完成此操作后,您只需确保重新计算相应的部分/插图,以便支持纵向和横向方向。

Then, use the collectionView:layout:insetForSectionAtIndex: delegate method to set the margins for your second section so as it appears to be vertically centered. Once you've done this, you just need to ensure you recompute the appropriate section divisions/insets so both portrait and landscape orientations can be supported.

有一些类似的问题在这里 - 如何居中对齐UICollectionView的单元格? - 即关于插入方法的更多细节,尽管它并不是在尝试做同样的事情。

There is a somewhat similar question here - How to center align the cells of a UICollectionView? - that goes into more details about the inset methods, although it's not quite trying to do the same thing that you are.

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

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