网格UICollectionView除了使用流布局,还可以使用自定义布局。实现自定义布局需要继承UICollectionViewLayout,同时还要重载下面的三个方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// 这个方法返回每个单元格的位置和大小
override
func
layoutAttributesForItemAtIndexPath(indexPath:
NSIndexPath
)
->
UICollectionViewLayoutAttributes
? {
}
// 返回内容区域总大小,不是可见区域
collectionViewContentSize() ->
CGSize
{
}
// 返回所有单元格位置属性
layoutAttributesForElementsInRect(rect:
CGRect
)
-> [
]? {
}
|
下面实现一个自定义布局的例子,单元格有大小两种。网格从上到下,先是左边一个大单元格右边两个小单元格,接着左边两个小单元格右边一个大单元格,依次同上循环排列。
效果图如下:
--- 自定义布局CustomLayout.swift ---
import
UIKit
/**
* 这个类只简单定义了一个section的布局
*/
class
CustomLayout
:
UICollectionViewLayout
{
// 内容区域总大小,不是可见区域
{
return
CGSizeMake
(collectionView!.bounds.size.width,
CGFloat
(collectionView!.numberOfItemsInSection(0) * 200 / 3 + 200))
}
// 所有单元格位置属性
)
]? {
var
attributesArray = [
]()
let
cellCount =
self
.collectionView!.numberOfItemsInSection(0)
for
i
in
0..<cellCount {
indexPath =
(forItem:i,inSection:0)
attributes =
.layoutAttributesForItemAtIndexPath(indexPath)
attributesArray.append(attributes!)
}
return
attributesArray
}
// 这个方法返回每个单元格的位置和大小
)
? {
//当前单元格布局属性
attribute =
(forCellWithIndexPath:indexPath)
//单元格外部空隙,简单起见,这些常量都在方法内部定义了,没有共享为类成员
//let itemSpacing = 2
linespacing = 5
//单元格边长
largeCellSide:
= 200
smallCellSide:
= 100
//内部间隙,左右5
insets =
UIEdgeInsetsMake
(2,5,2,5)
//当前行数,每行显示3个图片,1大2小
line:
Int
= indexPath.item / 3
//当前行的Y坐标
lineOriginY = largeCellSide *
(line) +
(linespacing * line)
+ insets.top
//右侧单元格X坐标,这里按左右对齐,所以中间空隙大
rightLargeX = collectionView!.bounds.size.width - largeCellSide - insets.right
rightSmallX = collectionView!.bounds.size.width - smallCellSide - insets.right
// 每行2个图片,2行循环一次,一共6种位置
if
(indexPath.item % 6 == 0) {
attribute.frame =
CGRectMake
(insets.left,lineOriginY,largeCellSide,
largeCellSide)
}
else
(indexPath.item % 6 == 1) {
(rightSmallX,smallCellSide,
smallCellSide)
(indexPath.item % 6 == 2) {
lineOriginY + smallCellSide + insets.top,smallCellSide)
(indexPath.item % 6 == 3) {
smallCellSide )
(indexPath.item % 6 == 4) {
(indexPath.item % 6 == 5) {
(rightLargeX,
largeCellSide)
}
attribute
}
/*
//如果有页眉、页脚或者背景,可以用下面的方法实现更多效果
func layoutAttributesForSupplementaryViewOfKind(elementKind: String!,
atIndexPath indexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes!
func layoutAttributesFordecorationViewOfKind(elementKind: String!,
atIndexPath indexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes!
*/
--- 主页面 ViewController.swift ---
|