? ? 最近開發(fā)用到UICollectionView,需求是橫向滑動,根據(jù)服務(wù)端傳過來的數(shù)據(jù),確定cell數(shù)量,以及根據(jù)每條數(shù)據(jù)的大小確定cell的寬度,點(diǎn)擊的cell高亮顯示。
? ? 使用代理方法
```Objective-c
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
```
????當(dāng)拿到數(shù)據(jù)模型的時(shí)候,即利用該模型的計(jì)算方法直接計(jì)算文本寬度,并賦值給數(shù)據(jù)模型的width屬性,在上面的代理方法中,寬度直接返回model.witdh,return CGSizeMake{self.dataSource[indexPath.row].width, height}。//高度一樣如果需要自適應(yīng)也可利用此方法。
```Objective-c
- (CGSize)collectionView:(nonnullUICollectionView*)collectionView layout:(nonnullUICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(nonnullNSIndexPath*)indexPath
{
if(self.dataSource) {
Model *model = (Model*)self.dataSource[indexPath.row];
returnCGSizeMake(model.width,28);
}else{
returnCGSizeMake(0,0);
}
}
```
????根據(jù)字符串計(jì)算出他應(yīng)該占據(jù)的寬度,需要兩個(gè)參數(shù),該字符串和想設(shè)置的字號大小,在此不再贅述。
```Objective-c
- (NSInteger)calculateWidth:(NSString*)routeDesc
{
CGSizesize = [routeDesc sizeWithFont:font];
returnsize.width+15;// +15兩邊留間距
}
- (CGSize)sizeWithFont:(UIFont*)font
{
if(self.length==0)
{
returnCGSizeZero;
}
NSDictionary* attrDic = [NSDictionarydictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
CGSizesize = [selfsizeWithAttributes:attrDic];//sizeWithAttributes is the default suggested replace method for selector(sizeWithFont:)
returnsize;
}
```
????高亮選擇根據(jù)model的isSelect屬性判斷文本以及cell邊框的顏色(為yes時(shí)是綠色,其他情況灰色),并在bindModel給cell綁定數(shù)據(jù)的方法中進(jìn)行設(shè)置。
? ? 小結(jié):自定義的UICollectionViewCell,實(shí)例方法必須實(shí)現(xiàn)initWithFrame,在設(shè)置該cell的邊框顏色才會有效,如果只實(shí)現(xiàn)init方法的話,設(shè)置cell.contentView的border之類的屬性不會有效。