A relatively new feature of iOS is the UICollectionViews.
The UICollectionView allows the programmer to arrange the data into cells, which in turn can be arranged in grids. The photos in the photo gallery of phone can be seen in thumbnails, arranged in a gird like pattern.
The UICollectionView operates in a very similar way to the UITableVIew. Basically it is a collection of cells that are displayed on the screen according to the properties defined by the programmer. The cells can be provided by a custom cells class giving the programmer the independence of customizing the contents and the appearance of the cells as required.
The process of implementing the UICollectionView is as usual.
- The programmer needs to make the
IBOutlet of the UICollectionView.
- Add the UICollectionView to the
Interface Builder.
- Include the
UICollectionViewDataSource,
UICollectionViewDelegate and the
UICollectionViewDelegateFlowLayout.
And declare an array to feed data to
the cells of the UICollectionView.
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UICollectionView *galleryCollectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
In the .m file of the ViewController populate the array, which in turn will populate the cells of the UICollectionView.
Then program the flow layout of the collection view as given below.
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(80, 80)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.galleryCollectionView setCollectionViewLayout:flowLayout];
Now use the delegate and data source methods of the UICollectionView as follows.
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [dataArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cvCell";
CVCell *cell = (CVCell *)[galleryCollectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
NSString *cellData = [data objectAtIndex:indexPath.row];
[cell.titleLabel setText:cellData];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// Type your code here.
}
0 Comment(s)