无法使用objectAtIndex属性

时间:2016-02-19 08:37:04

标签: ios objective-c uicollectionviewcell

我尝试从网络加载一组图像并将其显示在集合视图中的屏幕上。以下是我的代码

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.layer.cornerRadius = 5;
    NSURL *url = [NSURL URLWithString:
                  @"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"];
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];

    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];

    //recipeImageView.image = [UIImage imageNamed:[recipePhotos objectAtIndex:indexPath.row] ];
    recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0] ]];
    return cell;
}

但我必须使用objectAtIndex:indexPath.row属性以及imageWithData,以便可以刷图像。我有什么方法可以使用objectAtIndex:indexPath.row和NSData dataWithContentsOfURL吗?

3 个答案:

答案 0 :(得分:2)

有什么用?

NSURL *url = [NSURL URLWithString:
              @"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];

无论如何,你接近解决方案......

if (recipPhotoUrl.count > indexPath.row)
{
    recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[indexPath.row]]];
}

但是,你仍然在main thread上进行此操作,而你肯定会阻止用户界面,滚动也不会顺畅。 它也不太确定,因为您在不检查数组是否具有足够的维度的情况下访问索引。

答案 1 :(得分:1)

您可以使用此功能:

 NSString *url_str = [NSString stringWithFormat: @"%@",[recipPhotoUrl objectAtIndex: indexPath.item]];
 NSURL *url = [NSURL urlWithString:url_str];
 recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];

答案 2 :(得分:0)

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 应放在一个通用函数中。例如 - (void)viewDidLoad,为图像添加属性引用。

recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0]]];

更改为

recipeImageView.image = self.image;