關(guān)于網(wǎng)易新聞首頁框架的開源demo有很多,基本上都是用UIScrollView實(shí)現(xiàn)的.基于UICollectionView有其獨(dú)特的優(yōu)點(diǎn),本文用UICollectionView的方式實(shí)現(xiàn)了網(wǎng)易新聞首頁輪播的效果.
1 效果圖展示
2 核心代碼
#pragma mark - 創(chuàng)建并設(shè)置UICollectionView
- (void)setUpCollectionView {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
// 設(shè)置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中添加控制器的內(nèi)容
[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時選中對應(yīng)的標(biāo)題
NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
UIButton *selectedBtn = self.titlesButton[index];
[self selectTitleButton:selectedBtn];
}