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

来源:互联网 发布:海南儋州网络诈骗 编辑:程序博客网 时间:2024/05/16 13:49

我的主页使用collectionview

1.- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    NewsCollectionViewCell *cell = [collectionViewdequeueReusableCellWithReuseIdentifier:@"mycell"forIndexPath:indexPath];

    NSString *img = [[NewListsharedInstance].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 = [superinitWithFrame:frame];

    self.title = [[UILabelalloc] initWithFrame:CGRectMake(0,0, SIZE.width,50)];

    [self.contentViewaddSubview:self.title];

    self.title.adjustsFontSizeToFitWidth =YES;

    self.title.font = [UIFont systemFontOfSize:13];

    self.title.textColor = [UIColorwhiteColor];

    self.title.numberOfLines =5;

    self.myIV = [[UIImageViewalloc] initWithFrame:CGRectMake(0,50, SIZE.width,SIZE.height -50)];

    [self.contentViewaddSubview:self.myIV];

    return self;

    

}

-(CGFloat)returnWithTitle:(NSString *)tit img:(NSString *)imgUrl{

    

    self.title.text =tit;

    //同步请求数据

    NSData *data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:imgUrl]];

    UIImage *img=[UIImageimageWithData: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){

    returnCGSizeMake(self.view.bounds.size.width/2-10,heigh);

    }else{

    returnCGSizeMake(self.view.bounds.size.width/2-10,180);

    }

}


0 0
原创粉丝点击