可以滾動的集合視圖,滾動集合視圖
這個demo寫的是將集合視圖添加到滾動視圖中,實現可以滑動的效果。
()
1.建立視圖,定義集合視圖和滾動視圖
1 #import "ViewController.h" 2 #import "MyCollectionViewCell.h"//自訂的一個collectionViewCell 3 #define MainWidth [UIScreen mainScreen].bounds.size.width 4 #define MainHeight [UIScreen mainScreen].bounds.size.height 5 6 @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate> 7 @property (nonatomic,strong)UICollectionView * collectView; 8 @property (nonatomic,strong)UIScrollView * scrollView; 9 @property (nonatomic,strong)UICollectionViewFlowLayout * collectVFL;10 @end
2.初始化我們定義的集合視圖和滾動視圖
1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 //設定底部滾動效果_1 4 self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,MainHeight-64-55, MainWidth-55 ,55)];//設定滾動視圖顯示在螢幕中的尺寸 5 self.scrollView.backgroundColor = [UIColor clearColor]; 6 self.scrollView.bounces = NO; 7 self.scrollView.contentSize = CGSizeMake((MainWidth-55)/3 * 5 , 55);//滾動視圖的總尺寸 8 [self.view addSubview:self.scrollView]; 9 10 //設定底部滾動效果_211 //UICollectionViewFlowLayout就是為集合視圖布局,它繼承於UICollectionViewLayout(相關屬性就不再這一一列舉,請自行尋找官方文檔)12 UICollectionViewFlowLayout * collectVFL = [[UICollectionViewFlowLayout alloc]init]; 13 collectVFL.itemSize = CGSizeMake((MainWidth-55)/3, 55);14 collectVFL.minimumLineSpacing = 0;15 collectVFL.minimumInteritemSpacing = 0;16 collectVFL.scrollDirection = UICollectionViewScrollDirectionHorizontal;17 self.collectVFL = collectVFL;18 19 UICollectionView * collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0,(MainWidth-55)/3*5 ,55) collectionViewLayout:collectVFL];20 self.collectView = collectView;21 collectView.backgroundColor = [UIColor whiteColor];22 collectView.delegate = self;23 collectView.dataSource = self;24 collectView.scrollEnabled =NO;25 //注意點:集合視圖在初始化後需要註冊26 [collectView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];27 //將集合視圖添加在滾動視圖上28 [self.scrollView addSubview:collectView];29 30 [self.view setBackgroundColor:[UIColor grayColor]];31 32 }
3.實現集合視圖的代理方法
1 #pragma mark - 集合視圖代理 2 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 3 return 5; 4 } 5 6 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 7 8 static NSString * ide = @"cell"; 9 MyCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ide forIndexPath:indexPath];10 11 cell.titleLabel.text = @"哈哈哈";12 cell.backgroundColor = [UIColor clearColor];13 cell.photoImage.image = [UIImage imageNamed:@"運行狀態@2x"];14 return cell;15 }16 17 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{18 NSLog(@"點擊的Item:%ld",indexPath.item);19 }
4.結束! 此文是小編第一次書寫部落格,有不足的地方還請大神指點改正。