Adding CollectionView to the controller
Initialize the CollectionView in the Viewdidload method of the Controller
static NSString *id = @ "Collectionviewcell";
-(void) Viewdidload {
[Super Viewdidload];
//Uicollectionview *collectionview = [[Uicollectionview alloc]initwithframe:self.view.bounds]; This initialization method cannot be compiled by
Uicollectionview *collectionview = [[Uicollectionview alloc]initwithframe:self.view.bounds collectionViewLayout:[[ Uicollectionviewflowlayout Alloc]init]]; //Do not use uicollectionviewlayout,uicollectionviewlayout here is the abstract base class, is dedicated to subclass inheritance; Uicollectionviewflowlayout is the most basic layout.
Collectionview.datasource = self;
Collectionview.delegate = self;
[Self.view Addsubview:collectionview];
A Collectionviewcell is typically customized because the system is prefabricated collectionviewcell, unlike Tableviewcell, which has Label,imageview, Collectionviewcell only 2 View:backgroundview and Selectedbackgroundview
[CollectionView registerclass:[Customcell class] Forcellwithreuseidentifier:id];
}
#pragma mark-collectionviewdatasource
-(Nsinteger) Numberofsectionsincollectionview: (Uicollectionview *) CollectionView
{
return 1; //As with TableView
}
-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberofitemsinsection: (NSInteger) Section
{
return self.photos.count; //As with TableView
}
-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) Indexpath
{
Customcell *cell = (Customcell *) [CollectionView dequeuereusablecellwithreuseidentifier:id ForIndexPath:indexPath];
//Do not need to write if (!cell) {initialize cell;}
///Indexpath.row, may collectionview layout more free, not like TableView is generally "line", so more people like to use Indexpath.item bar
[Cell.imagev setimage:[uiimage Imagenamed:self.photos[indexpath. Item]];
return cell;
}
Custom Collectionviewcell
CustomCell.h
@interface Customcell:uicollectionviewcell
@property (nonatomic, weak) Uiimageview *imagev;
@end
customcell.m
-(ID) initWithFrame: (CGRect) frame
{
self = [super Initwithframe:frame];
if (self) {
Uiimageview *imageview = [[Uiimageview alloc]init];
Imageview.frame = CGRectMake (5, 5, 40, 40);
[Self addsubview:imageview];
_imagev = ImageView;
}
return self;
}
Use of IOS Uicollectionview (create UI in code)