UICollectionView didSelectItemAtIndexPath,如何从cellForItemAtIndexPath传递随机图像?

时间:2014-12-29 20:27:47

标签: ios objective-c uicollectionview

我使用Parse数据库在我的UICollectionView中显示带有随机索引的图像数组,但是当用户选择项目时我需要在警报中显示它们,那么我如何才能正确地检索图像didSelectItemAtIndexPath ?!谢谢!!

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //static
    NSString *identifier = @"cell";

    AppDelegate *appDelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    int imgRandom = arc4random() % appDelegate.immaginihome.count;

    NSDictionary* dictionary = appDelegate.immaginihome[imgRandom];
    _eventImage = dictionary[@"ImmaginiHome"];

    if(_eventImage) { 

        [_eventImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {

            _image = [UIImage imageWithData:data];

            UIImageView *recipeImageView = [[UIImageView alloc]init];
            recipeImageView.image = _image;

            recipeImageView.frame=cell.bounds;

            recipeImageView.clipsToBounds = NO;
            recipeImageView.layer.shadowColor = [[UIColor blackColor] CGColor];
            recipeImageView.layer.shadowOpacity = 0.5;
            recipeImageView.layer.shadowOffset = CGSizeMake(2,3);
            recipeImageView.layer.drawsAsynchronously=YES;
            recipeImageView.layer.borderWidth = 2.0;
            recipeImageView.layer.borderColor = [UIColor whiteColor].CGColor;

            [cell addSubview:recipeImageView];
        }];
    }  // else if (_eventImage==NULL){}

    return cell;
}

1 个答案:

答案 0 :(得分:0)

简短回答

    NSString *const identifier = @"cell";

    -(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

        UIImage *image;
        for (UIView *view in [cell subviews]) {
            if ([view isKindOfClass:[UIImageView class]]) {
               image = [(UIImageView*)view image];
               break;
            }
        }

        if (image) {
            //do what you want to do
        } else {
            //something goes wrong
        }
    }

更好的回答 - 只需将您的随机图片存储在数组中,然后在

之后使用它
    NSMutableArray *randomImageNameList = [NSMutableArray array];
    NSDictionary* dictionary;
    NSUInteger count = [appDelegate.immaginihome count];
    NSString *imageNameKey = @"ImmaginiHome";
    for (int i = 0; i < count; i++) {
        dictionary = [appDelegate.immaginihome objectAtIndex:(arc4random() % count)];
        [randomImageNameList addObject:[dictionary objectForKey:imageNameKey];
    }