iOS:UICollectionView如何横向滚动

  • 这是最最基本的UICollectionView横向滚动的教学,代码很少,全在viewController.m里面编写,代码如下:
#import "ViewController.h"

static NSString *cellID = @"cell";

@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong) UICollectionView *myCollectionView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGRect collectionViewFrame= CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 100);
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置UICollectionView为横向滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 每一行cell之间的间距
    flowLayout.minimumLineSpacing = 50;
     // 每一列cell之间的间距
     // flowLayout.minimumInteritemSpacing = 10;
    // 设置第一个cell和最后一个cell,与父控件之间的间距
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
    
    //    flowLayout.minimumLineSpacing = 1;// 根据需要编写
    //    flowLayout.minimumInteritemSpacing = 1;// 根据需要编写
    //    flowLayout.itemSize = CGSizeMake(70, 70);// 该行代码就算不写,item也会有默认尺寸
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor redColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    _myCollectionView = collectionView;
    [self.view addSubview:collectionView];
    
    [self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellID];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 15;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    if (!cell ) {
        NSLog(@"cell为空,创建cell");
        cell = [[UICollectionViewCell alloc] init];
    }
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • 我本是抱着信任你的心情来选择和你共度余生 我也相信你的自行车后座上会有美丽风景 可如此这般 你却还要带我去沙漠 连...
    杨大敏敏子阅读 329评论 0 3
  • 梦醒了,不想被一直困扰在里面,不真实,但却有些是事实。 不喜欢一些人,但却被一些人误会,也最终孤独倍至。真难受,感...
    新绪阅读 196评论 0 0
  • 青青子衿,悠悠我心。 但为君故,沉吟至今。 ____ 大山君,阿荣来了! 2017年9...
    阿荣儿阅读 781评论 0 0