SpringBoard九宫格的实现 (基于UICollectionView)

来源:互联网 发布:淘宝哪家女装好看 编辑:程序博客网 时间:2024/05/17 07:49

SpringBoard九宫格的实现 (基于UICollectionView)

SpringBoard九宫格大概是这个样子的:(在游戏 Doty 中的选关界面)

DotyLevels

在我们的演示程序中,它在各个尺寸的 iPhone 上是这样的:

iPhone4S

4S

iPhone5S

5S

iPhone6

6

iPhone6P

6P

可以在 GitHub 上查看本 Demo 的完整源码,或 Clone 到本地编译运行。

实现这个效果,主要就是基于UIScrollView的横向分页滚动,和基于UICollectionView的布局。

基于UIScrollView的横向分页滚动,思路完全来自于 Apple 自带的官方示例 PageControl,它还做了一个分页的延迟加载,从而不需要一上来就加载所有页面。

基于UICollectionView的布局,主要就是计算好格子的大小和间距。示例中的要求是格子横向间距最小20点,纵向间距最小15点,格子保持宽高比为10:16,并且满足条件的情况下,优先按横向间距最小来计算格子大小,排列不下的话再按纵向间距最小计算格子大小。这里的关键点是,在考虑计算间距和大小的时候,UICollectionView容器的宽和高都要减一个像素来算,因为由于计算精度的缘故,如果不减一个像素来算,最终格子和间距的大小加起来可能比容器的宽或高要大一些。

float minGapH = 20.f;float minGapV = 15.f;float topOffset = 20.f;// avoid float number precision problemfloat innerWidth = self.collectionView.frame.size.width - 2 * minGapH - 1;float innerHeight = self.collectionView.frame.size.height - topOffset - 1;// try layout by minGapH firstfloat width = (innerWidth - 2 * minGapH) / 3.f;float height = width / aspectRaito;if (height * 3 + 2 * minGapV > innerHeight) {    // can't layout by minGapH, layout by minGapV    height = (innerHeight - 2 * minGapV) / 3.f;    width = height * aspectRaito;}float gapH = (innerWidth - 3 * width) / 2.f;float gapV = (innerHeight - 3 * height) / 2.f;UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;layout.itemSize = CGSizeMake(width, height);layout.minimumInteritemSpacing = gapH;layout.minimumLineSpacing = gapV;layout.sectionInset = UIEdgeInsetsMake(topOffset, minGapH, 0, minGapH);

完整的源码还是请大家移步至 GitHub 哦.

0 0
原创粉丝点击