UICollectionViewCell 修改cell间距

UICollectionView 的布局默认是当前行内适应,如果cell的宽度超过当前的行宽度就会放到下一行,但是当前行内的多个cell会等距离分布,而不能像效果图中等间距靠left 或者right分布。

如图效果
/// 让列间距固定为minimumInteritemSpacing
class AiUgcReportFlowLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let attris = super.layoutAttributesForElements(in: rect) {
            for (i, att) in attris.enumerated() {
                if i>0 {
                    let cur = att
                    let pre = attris[i-1]
                    // 这里 indexPath 一定要判断,坑了半天,fuck
                    if cur.indexPath == pre.indexPath {
                        let preMaxX = pre.frame.maxX
                        //根据  maximumInteritemSpacing 计算出的新的 x 位置
                        let targetX = preMaxX + self.minimumInteritemSpacing;
                        if targetX < cur.frame.maxX && (targetX+cur.frame.width) < self.collectionViewContentSize.width {
                            var curFrame = cur.frame
                            curFrame.origin.x = targetX
                            cur.frame = curFrame
                        }
                    }
                    
                }
            }
            return attris
        }
        return super.layoutAttributesForElements(in: rect)
    }
}

😀 😀 😀 😀 提供oc 版本,直接用吧骚年😀 😀 😀

- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attris = [super layoutAttributesForElementsInRect:rect];
    for (int i = 0; i< attris.count; i++) {
        if (i>0) {
            
            UICollectionViewLayoutAttributes *curAtt = attris[i];
            UICollectionViewLayoutAttributes *preAtt = attris[i-1];
            // 这里 indexPath 一定要判断,坑了半天,fuck
            if (curAtt.indexPath == preAtt.indexPath) {
                CGFloat curMaxX = curAtt.frame.origin.x+curAtt.frame.size.width;
                CGFloat preMaxX = preAtt.frame.origin.x+preAtt.frame.size.width;
                CGFloat targetX = preMaxX + self.minimumInteritemSpacing;
                if ((targetX < curMaxX) && (targetX+curAtt.frame.size.width) < self.collectionView.bounds.size.width) {
                    CGRect curFrame = curAtt.frame;
                    curFrame.origin.x = targetX;
                    curAtt.frame = curFrame;
                }
            }
        }
    }
    
    return attris;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 网页布局(layout)是CSS的一个重点,传统的方式是基于盒子模型,依赖display、position、flo...
    JunChow520阅读 1,138评论 0 0
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,603评论 28 53
  • 信任包括信任自己和信任他人 很多时候,很多事情,失败、遗憾、错过,源于不自信,不信任他人 觉得自己做不成,别人做不...
    吴氵晃阅读 6,226评论 4 8
  • 步骤:发微博01-导航栏内容 -> 发微博02-自定义TextView -> 发微博03-完善TextView和...
    dibadalu阅读 3,181评论 1 3
  • 回这一趟老家,心里多了两个疙瘩。第一是堂姐现在谈了一个有妇之夫,在她的语言中感觉,她不打算跟他有太长远的计划,这让...
    安九阅读 3,532评论 2 4