UICollectionView设置最大间距

应用中用UICollectionView应该不少了,和UITableView相似,除了Delegate和DataSource,注意的地方还有设置UICollectionViewFlowLayout。有时候设置最大水平距离和设置最大垂直距离,和cell的大小满足不了需求,还要自定义UICollectionViewFlowLayout。
自定义一个类CustomFlowLayout,继承UICollectionViewFlowLayout类,然后在- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect方法添加以下代码

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray * attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    
    //从第二个循环到最后一个
    for (NSInteger i = 1 ; i < attributes.count ; i ++ )
    {
        //当前的attribute
        UICollectionViewLayoutAttributes * currentLayoutAttributes = attributes[i];
        
        //上一个attribute
        UICollectionViewLayoutAttributes * prevLayoutAttributes = attributes[i - 1];
        
        //设置的最大间距,根绝需要修改
        CGFloat maximumSpacing = 6.0;
        
        //前一个cell的最右边
        CGFloat origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        
        //如果当前一个cell的最右边加上我们的想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置
        //不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有的cell的x值都被加到第一行最后一个元素的后面了
        if (origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width)
        {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
        
    }
    
    return attributes;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容