网络加载完,想要获取图片的宽,效果瀑布流

我的主页使用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);

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值