如何在UICollectionView中使用来自url的图像?

时间:2013-10-25 14:53:00

标签: iphone objective-c ios6 nsarray uicollectionview

我的代码是:

- (void)viewDidLoad
{
   [super viewDidLoad];

   UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
   collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(30, 20, 260, 270) collectionViewLayout:layout];
   [collectionView setDataSource:self];
   [collectionView setDelegate:self];

   [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
   [collectionView setBackgroundColor:[UIColor clearColor]];

   [self.view addSubview:collectionView];

   string1=[NSString stringWithFormat:url];
   NSURL *jsonUrl = [NSURL URLWithString:string1];
   NSData *data = [NSData dataWithContentsOfURL:jsonUrl];
   UIImage *image1 =[[UIImage imageWithData:data]autorelease];
   set=[NSArray arrayWithObject:image1];
   tmp= [[NSMutableArray alloc] init];

        for (int i=1; i<[set count]; i++)
        {
            [tmp addObject:[set objectAtIndex:i+1]];
        }


 }
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [tmp count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
      UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[tmp objectAtIndex:indexpath.row]]] ;
    cell.backgroundColor=[UIColor clearColor];

    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80, 80);
}

我觉得这个动作不起作用或者我伤害了事情

cell.backgroundview =[UIImageView alloc]initwithimage:[UIImage imageNamed:[tmp objectAtIndex:indexPath.row]]];

2 个答案:

答案 0 :(得分:0)

您在viewDidLoad

中做错了什么

你唯一需要的是为你的UICollectionView设置一个颜色,所以改变你的代码,例如:

[collectionView setBackgroundColor:[UIColor redColor]];

假设您的数组tmp是一个图像名称数组(例如“myImage.png”),并在viewDidLoad结束前重新加载您的收藏视图;

[collectionView reloadData];

答案 1 :(得分:0)

我有这样的解决方案:

 cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"nameImage.jpg"]];