UICollectionView实现网易新闻首页框架

关于网易新闻首页框架的开源demo有很多,基本上都是用UIScrollView实现的.基于UICollectionView有其独特的优点,本文用UICollectionView的方式实现了网易新闻首页轮播的效果.

1 效果图展示

2 核心代码

#pragma mark - 创建并设置UICollectionView
- (void)setUpCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置cell尺寸
    flowLayout.itemSize = CGSizeMake(JLScreenW, JLScreenH - 64-44);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor blueColor];
    collectionView.frame = CGRectMake(0, 64+44, self.view.frame.size.width, JLScreenH - 64-44);
    collectionView.pagingEnabled = YES;
    _collectionView = collectionView;
    [self.view addSubview:collectionView];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark - collectionView datasource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.childViewControllers.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

   // cell中添加控制器的内容
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    UIViewController *vc = self.childViewControllers[indexPath.item];
      vc.view.frame = cell.bounds;
    [cell.contentView addSubview:vc.view];
  
    return cell;
}

#pragma mark - collectionView delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
 // 滚动cell时选中对应的标题    
    NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
    UIButton *selectedBtn = self.titlesButton[index];    
     [self selectTitleButton:selectedBtn];
}

3 源码地址:

https://github.com/xiaonvhai-xiansheng/JLNetEseayDemo

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,976评论 25 708
  • Babybus-u3d技术交流-【Unity技巧】调整贴图质量 写在前面当我们在Unity中,使用图片进行2D显示...
    Babybus_Unity阅读 6,502评论 0 1
  • 大任丘本地微博朋友圈7天内话题汇总: 文化道菜市场着大火了 金台园美少妇跳楼了[发抖] 直升机空降把小盆友...
    67fbaec5208f阅读 249评论 0 0
  • 曾几何时,我曾梦想着成为这场婚礼的新娘,身着红色嫁衣,成为你今后的另一半; 曾几何时,我曾幻想着我们今后的小生活,...
    悦书童阅读 284评论 0 0