IOS基礎_ UICollectionView的簡單使用

和表格視圖類似 UICollectionView的使用有兩種方法

一種是繼承UICollectionViewController,這個Controller會自帶一個UICollectionView;

另外一種是創建一個UIConllectionView 視圖放在普通的UIViewController裏面。

我們用第二種


首先聲明先聲明一個重用標示  和實現委託

#define _CELL @"acell"

@interface yxpViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>


然後初始化UICollectionVIew

- (void)initCollectionView

{

    //先實例化一個層

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];

    

    //創建一屏的視圖大小

    UICollectionView *collectionView=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];

    

    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:_CELL];

    collectionView.backgroundColor=[UIColor whiteColor];

    collectionView.delegate=self;

    collectionView.dataSource=self;

    

    [self.view addSubview:collectionView];

}


實現代理方法

#pragma mark --UICollectionViewDataSource

//定義展示的UICollectionViewCell的個數

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 31;

}

//定義展示的Section的個數

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

//每個UICollectionView展示的內容

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:_CELL forIndexPath:indexPath];

    

    cell.backgroundColor = [UIColor colorWithRed:((arc4random()%255)/255.0) green:((arc4random()%255)/255.0) blue:((arc4random()%255)/255.0) alpha:1.0f];

    

    return cell;

}


#pragma mark --UICollectionViewDelegate

//UICollectionView被選中時調用的方法

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    cell.backgroundColor = [UIColor colorWithRed:((arc4random()%255)/255.0) green:((arc4random()%255)/255.0) blue:((arc4random()%255)/255.0) alpha:1.0f];

}

//返回這個UICollectionViewCell是否可以被選擇

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}



#pragma mark --UICollectionViewDelegateFlowLayout

//定義每個UICollectionView 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    return CGSizeMake(90, 90);

}

//定義每個UICollectionView 的邊距

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    return UIEdgeInsetsMake(10, 10, 10,10);

}


這樣一個簡單地UICollection視圖就完成了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章