UICollectionView建立實例

UICollectionView 和 UICollectionViewController 類是iOS6 新引進的API,用於展現集合視圖,佈局更加靈活,可實現多列布局,用法相似於UITableView 和 UITableViewController 類。佈局

使用UICollectionView 必須實現UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout這三個協議。spa

 

下面先給出經常使用到的一些方法。(只給出經常使用的,其餘的能夠查看相關API) orm

  1. #pragma mark -- UICollectionViewDataSource   it

  1. //定義展現的UICollectionViewCell的個數  io

  2. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  queue

  3. {  方法

  4.     return 30;  layout

  5. }   協議

  1. //定義展現的Section的個數  margin

  2. -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  

  3. {  

  4.     return 1;  

  5. }   

  1. //每一個UICollectionView展現的內容  

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

  3. {  

  4.     static NSString * CellIdentifier = @"GradientCell";  

  5.     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];  

  6.   

  7.     cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];  

  8.     return cell;  

  9. }   

  1. #pragma mark --UICollectionViewDelegateFlowLayout   

  1. //定義每一個UICollectionView 的大小  

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

  3. {  

  4.     return CGSizeMake(96, 100);  

  5. }   

  1. //定義每一個UICollectionView 的 margin  

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

  3. {  

  4.     return UIEdgeInsetsMake(5, 5, 5, 5);  

  5. }   

  1. #pragma mark --UICollectionViewDelegate   

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

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

  3. {  

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

  5.     cell.backgroundColor = [UIColor whiteColor];  

  6. }   

  1. //返回這個UICollectionView是否能夠被選擇  

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

  3. {  

  4.     return YES;  

  5. }  

相關文章
相關標籤/搜索