Syed Munim Raza Syed Munim Raza - 4 months ago 63
iOS Question

2D NSMutableArray in UICollectionView

I'm new in IOS and I don't have idea that how to populate my 2D array in

collectionView
.

**How Will I display following in collectionView using Labels.

myArray[0]->1,2,3,4,5
myArray[1]->6,7,8,9
myArray[2]->10,11,12,15


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

// What to call here as this is 2D?

return self.myArray.count;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *simpleId= @"CollectionViewCell";
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleId forIndexPath:indexPath];

//What to write here ? Cell contain 1 Label
}

Answer

Try to do like this (as @Larme suggested)-

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

   NSString *simpleId= @"CollectionViewCell";
   TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleId forIndexPath:indexPath];

   cell.lbl.text= [NSString stringWithFormat:@"%@",[[self.myArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];

   return cell;

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

     return self.myArray.count;
}


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

    return [[self.myArray objectAtIndex:section] count]
}

In your 2D array myArray[0] is first section consist 5 value, myArray[1] is second section consist 4 values and myArray[2] is second section consist 5 values. So 2D Array can be easily managed by numberOfSection and numberOfItemsInSection methods. Hope this will help you..