與UITableViewCell不同男摧,UICollectionViewCell中默認(rèn)情況下沒有什么附帶的控件雷猪,因此纵隔,如果在開發(fā)中使用到CollectionView暮现,100%都需要定制。
1铐望、新建自定義UICollectionViewCell類
添加控件:根據(jù)項(xiàng)目開發(fā)的需要冈涧,設(shè)計(jì)界面;
設(shè)置自動(dòng)布局約束:由于需要適配多種尺寸的屏幕正蛙,所以在添加約束時(shí)督弓,盡量不要設(shè)置子控件的絕對高度和寬度,否則當(dāng)屏幕尺寸不同時(shí)乒验,會(huì)影響顯示效果愚隧。盡量設(shè)置邊距約束。
連線锻全,添加屬性:把自定義Cell中的控件狂塘,連線到.h文件中,以便提供數(shù)據(jù)源鳄厌。
#import
@interfaceMYCollectionCell:UICollectionViewCell
@property(weak,nonatomic)IBOutletUIImageView*photoImageView;
@property(weak,nonatomic)IBOutletUILabel*label;
@end
2荞胡、設(shè)置Cell的數(shù)據(jù)源
在cellForItemAtIndexPath:方法中,設(shè)置Cell的UI控件數(shù)據(jù)源了嚎。
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
MYCollectionCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
cell.backgroundColor=[UIColoryellowColor];
cell.photoImageView.image=[UIImageimageNamed:@"photo"];
cell.label.text=[NSStringstringWithFormat:@"%d-%d",indexPath.section,indexPath.row];
returncell;
}