CollectionView的數(shù)據(jù)源協(xié)議為集合視圖的Cell提供了數(shù)據(jù)來源站宗,其基本使用方法與TableView的數(shù)據(jù)源方法類似函喉,但區(qū)別在于集合視圖需要提前注冊Cell酪碘。
1帖世、注冊Cell
在viewDidLoad方法中,對Cell進行預(yù)先注冊棍苹,可以通過代碼來創(chuàng)建Cell无宿,也可以通過XIB來創(chuàng)建Cell,兩種創(chuàng)建方式分別對應(yīng)不同的注冊方法枢里。
-(void)registerClass:(nullableClass)cellClass forCellWithReuseIdentifier:(NSString*)identifier;
-(void)registerNib:(nullableUINib*)nib forCellWithReuseIdentifier:(NSString*)identifier;
示例:
staticNSString*cellID=@"MYCollectionCell";
[self.collectionView registerNib:[UINibnibWithNibName:@"MYCollectionCell"bundle:[NSBundlemainBundle]]forCellWithReuseIdentifier:cellID];
2孽鸡、數(shù)據(jù)源方法實現(xiàn)
設(shè)置CollectionView的DataSource屬性,指定數(shù)據(jù)源栏豺;
實現(xiàn)如下方法:
@protocolUICollectionViewDataSource
@required
-(NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section;
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath;
@optional
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView;
@end
示例:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView
{
return2;
}
-(NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section{
return9;
}
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
MYCollectionCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
cell.backgroundColor=[UIColoryellowColor];
returncell;
}