I had worked with UITableView
but I have never ever use of UICollectionView
in my apps. So I want to create UICollectionView
programmatic
The problem is in your collectionView:cellForItemAtIndexPath:
method. You are adding those subviews every single time a cell is reused, on top of each other.
You should create a UICollectionViewCell
subclass and add all of the extra subviews you want into its initializer. This will make sure they only get added once.
sample code:
Here is an example of how you would subclass UICollectionViewCell
@interface MyCustomCell : UICollectionViewCell
@property (nonatomic, strong) UILabel *customLabel;
@property (nonatomic, strong) UIImageView *customImageView;
@end
// in implementation file
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// initialize label and imageview here, then add them as subviews to the content view
}
return self;
}
Then when you are grabbing a cell you just do something like:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
if (cell.selected)
cell.backgroundColor = [UIColor lightGrayColor]; // highlight selection cell
else
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-grid.png"]]; // Default Cell
cell.customImageView.image = // whatever
cell.customLabel.text = // whatever
return cell;
}