collcetionView 横向分页排版(oc版)

引言

collcetionView 横向分页排版现在在App首页头部视图菜单里面用的比较多。今天分享一哈实现方法。

true.png

这种界面分分钟肯定会想到用collectionview来做,实现也很简单,但是结果你得到的会是下面这种界面(顺序完全不是你想要的)

false.png

这是collectionview横向滑动默认的布局方式,想要实现按照你想要的顺序的布局方式的话必须自定义collectionviewflowlayout子类来实现了,废话不多说直接上代码。

- (void)prepareLayout {
    [super prepareLayout];
    [self.attArray removeAllObjects];
    //定义当前行数、页数变量
    NSInteger lineNum = 1;
    NSInteger page = 0;
    //定义itemsize
    NSInteger originX = self.collectionView.bounds.size.width;
    CGFloat attWidth = (SCREEN_WIDTH - 22) / 5;
    CGFloat attHeight = (SCREEN_WIDTH - 22) / 5.5;
    
    NSInteger items = [self.collectionView numberOfItemsInSection:0];
    
    for (NSInteger i = 0; i < items; i ++) {
        NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
      //因为我是一行显示5个,所以取计算5的余数,如果==0就换行,一来i = 0,所以lineNum初始值为0,从第一行开始添加
        if (i % 5 == 0) {
            lineNum = lineNum == 0 ? 1 : 0;
        }
       //超过10个就加一页,让x坐标加上页数 * collectionview宽度
        if ((NSInteger)(i / 10) >= 0) {
            page = i / 10;
        }
        //计算frame
        att.frame = CGRectMake((i % 5) * attWidth + (originX * page), lineNum * (attHeight + self.minimumInteritemSpacing) + self.sectionInset.top, attWidth, attHeight);
        
        [self.attArray addObject:att];
    }
}

- (CGSize)collectionViewContentSize {
    NSInteger items = [self.collectionView numberOfItemsInSection:0];
    NSInteger pages = 0;
    if (items % 10 == 0) {
        pages = items / 10;
    } else {
        pages = items / 10 + 1;
    }
    return CGSizeMake(CGRectGetWidth(self.collectionView.frame) * pages, 0);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *array = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes *att in self.attArray) {
        if (CGRectIntersectsRect(rect, att.frame)) {
            [array addObject:att];
        }
    }
    return array;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,067评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • 写字时闲散心境极为难得。人类社会吵吵扒火的,无非是穷人想发财,富人想纵欲。写书法的朋友大多也落了这个窠臼,即便希求...
    晓暐阅读 784评论 8 17
  • Day3 一朝“圣人”:昨天是八一建军节,和平年代默默守护我们的军人格外耀眼,朋友圈更是满满的崇拜。 我正好去拜访...
    跑步的心情阅读 351评论 0 1
  • 男人是家庭里的中流砥柱,但相较于女性,大多数男性对于健康的话题并不感冒,这就很容易导致,在忙碌工作的时候,一些疾病...
    营养师高亚军阅读 395评论 1 1