美文网首页ios开发整理iOS开发征服iOS
使用CollectionView实现横向滚动(一)

使用CollectionView实现横向滚动(一)

作者: Cooperluffy丨路飞 | 来源:发表于2016-10-27 13:25 被阅读29595次

平时使用UITableView比较多,一直对CollectionView不怎么熟悉,为了加深对CollectionVew的理解,特意写几个小的Demo熟悉一下。

colectionView.gif

关键代码:

 _collectionView = ({
        
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.itemSize = CGSizeMake(130, 130);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 2;

        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 244, self.view.frame.size.width,130) collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.scrollsToTop = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        [collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:kMyCollectionViewCellID];
        [self.view addSubview:collectionView];
        collectionView;
    });


设置代理

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 8;
}


- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
     return [collectionView dequeueReusableCellWithReuseIdentifier:kMyCollectionViewCellID forIndexPath:indexPath];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [(MyCollectionViewCell *)cell configureCellWithPostURL:@"postImage.jpg"];
}

```

[GitHub地址: https://github.com/JnLuffy/CollectionViewDemo1](https://github.com/JnLuffy/CollectionViewDemo1)

相关文章

网友评论

  • 啊哈哈哈哈哈群:楼主 你写的这个滑动是只有一个section的情况下才可以使用,而实际开发中如果有横向滑动的需求 都是某个section的滑动 ,所以感觉这样写很鸡肋。
  • 王天琦:按照这种方式写了,不过遇到了一个致命的问题。
    横向滑动,section(区头)的默认位置是居左的,没有办法改到上边
  • hhgvg:这个是有bug的 滚动过程中很明显这个cell的位置发生了变化 偏移了
    Cooperluffy丨路飞:什么意思?没看出来呢
  • 小灬博:我想让他整页滚动,怎么实现,我这是一个一个cell 滚动的
    剑客十八:大兄弟,整页滚动有demo吗?
  • tinaH:怎么让collectionview不滚动
  • 863c73f31933:楼上,我这边也是横向写的collectionview,横向滑动的时候某些cell没有刷新,你知道是为什么不?
    Cooperluffy丨路飞:@SunlightInMyLif 查看一下collection的frame和layout,有可能是只是你看到了,其实对于CollectionView来说,这2个Cell并不是可见的。
    863c73f31933:collection view横向滑动时候的刷新,没使用reload,自动到了cellforitem里面,出现我上面说的问题,在cellforitem里面打印indexpath有2个没打印出来,但是页面上这两个都显示出来了
    Cooperluffy丨路飞:reloadData刷新吗?使用局部刷新试试 reloadItemsAtIndexPaths

本文标题:使用CollectionView实现横向滚动(一)

本文链接:https://www.haomeiwen.com/subject/xwnjuttx.html