我的主页使用collectionview
1.- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mycell" forIndexPath:indexPath];
NSString *img = [[NewList sharedInstance].news[indexPath.row]orignalImg];
//高度,在这里,我的cell想要展示图片和标题
heigh =[cell returnWithTitle:[[NewList sharedInstance].news[indexPath.row] title] img:img];
return cell;
}
2.自定义的cell UICollectionViewCell
//如果把创建title和image写在下边就会出现title重叠
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
self.title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SIZE.width, 50)];
[self.contentView addSubview:self.title];
self.title.adjustsFontSizeToFitWidth = YES;
self.title.font = [UIFont systemFontOfSize:13];
self.title.textColor = [UIColor whiteColor];
self.title.numberOfLines = 5;
self.myIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, SIZE.width, SIZE.height - 50)];
[self.contentView addSubview:self.myIV];
return self;
}
-(CGFloat)returnWithTitle:(NSString *)tit img:(NSString *)imgUrl{
self.title.text =tit;
//同步请求数据
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
UIImage *img=[UIImage imageWithData:data];
//获取图片的宽
CGFloat sourcewidth = img.size.width;
//获取图片的高
CGFloat sourceheight = img.size.height;
//比例
CGFloat scale = (Width/2-10)/sourcewidth;
self.myIV.image=img;
//通过比例计算,得到图片的高+标题的高,回传,
return scale*sourceheight+50;
}
3.特别注意,如果网络获取图片,图片有时不一定正确的获取出来,必须判断图片回传是否有值,没有的话,手动定义cell的高,不然程序会崩
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
if(heigh>0){
return CGSizeMake(self.view.bounds.size.width/2-10, heigh);
}else{
return CGSizeMake(self.view.bounds.size.width/2-10, 180);
}
}