Monday, 20 June 2016

Collection View Controller in iOS - Objective C

1) Create single view application
2) Select Story Board, delete existing view controller
3) Drag & Drop UICollectionViewController in to StoryBoard
4) Delete existing viewcontroller.h and viewcontroller.m
5) Add NewFile --> Enter new class name as mycollectionviewcontroller.h--> subclass of  UICollectionViewController
6) In Main.Storyboard add custom class

7) Select UICollectionview cell -->enter identifier as "Cell"

8) Drag & Drop Image view on UICollectionviewcell -->change Tag Value to "100"


9) Drag & drop Label on UICollectionview cell -->change Tag Value to "101"

10) Add below code in Mycollectionviewcontroller.h

@interface MyCollectionViewController : UICollectionViewController
{
    NSArray *devicePhotos;
    NSArray *deviceNameArr;
}

@end



11) Add below code in my controller.m
       1) Add below code in viewdidload

 devicePhotos=[[NSArray alloc]initWithObjects:@"1.jpeg",@"2.jpeg",@"3.jpeg",@"4.jpeg",@"1.jpeg",@"2.jpeg",@"3.jpeg",@"4.jpeg",@"1.jpeg",@"2.jpeg",@"3.jpeg",@"4.jpeg",nil];
    deviceNameArr=[[NSArray alloc]initWithObjects:@"iPhone",@"iPad",@"iPod",@"iPadmini", @"iPhone",@"iPad",@"iPod",@"iPadmini", @"iPhone",@"iPad",@"iPod",@"iPadmini", nil];


12) Add below methods in view controller.m

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return devicePhotos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    // product Image
    UIImageView *iv = (UIImageView *)[cell viewWithTag:100];
    iv.image = [UIImage imageNamed:[devicePhotos objectAtIndex:indexPath.row]];
    // Product Name
    UILabel *lbl=(UILabel *)[cell viewWithTag:101];
    lbl.text=[deviceNameArr objectAtIndex:indexPath.row];
    
    return cell;

}

13) Build & Run the project

Reference: http://www.appcoda.com/ios-programming-uicollectionview-tutorial



No comments:

Post a Comment