UICollectionView实现网易新闻首页框架
2017-03-21 本文已影响320人
小码码
关于网易新闻首页框架的开源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];
}