應(yīng)用中用UICollectionView應(yīng)該不少了十饥,和UITableView相似何暮,除了Delegate和DataSource沈条,注意的地方還有設(shè)置UICollectionViewFlowLayout刃鳄。有時(shí)候設(shè)置最大水平距離和設(shè)置最大垂直距離厌衔,和cell的大小滿足不了需求,還要自定義UICollectionViewFlowLayout夺艰。
自定義一個(gè)類CustomFlowLayout芋哭,繼承UICollectionViewFlowLayout類,然后在- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect方法添加以下代碼
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray * attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
//從第二個(gè)循環(huán)到最后一個(gè)
for (NSInteger i = 1 ; i < attributes.count ; i ++ )
{
//當(dāng)前的attribute
UICollectionViewLayoutAttributes * currentLayoutAttributes = attributes[i];
//上一個(gè)attribute
UICollectionViewLayoutAttributes * prevLayoutAttributes = attributes[i - 1];
//設(shè)置的最大間距劲适,根絕需要修改
CGFloat maximumSpacing = 6.0;
//前一個(gè)cell的最右邊
CGFloat origin = CGRectGetMaxX(prevLayoutAttributes.frame);
//如果當(dāng)前一個(gè)cell的最右邊加上我們的想要的間距加上當(dāng)前cell的寬度依然在contentSize中,我們改變當(dāng)前cell的原點(diǎn)位置
//不加這個(gè)判斷的后果是厢蒜,UICollectionView只顯示一行霞势,原因是下面所有的cell的x值都被加到第一行最后一個(gè)元素的后面了
if (origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width)
{
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attributes;
}