Wesley Smith
Wesley Smith

Reputation: 19571

Set an image to many UIImageViews

Say I have 60-70 UIImageViews and I want to dynamically load the same image into all of them at the same time (so to speak).

For example, if I were working on a web page with 60-70 divs and I wanted to give them all a background image I would give them all a class of myDivs and call `$('.myDivs').css('background-image', 'url(' + imageUrl + ')');

I know how to set a UIImageView's image but is there an easy way to set a bunch at once in Objective C?

I did try searching but I was flooded with a ton of stuff that is really unrelated.

Upvotes: 0

Views: 127

Answers (2)

Raz
Raz

Reputation: 2643

It depends on the way you wish to display the imageView(s). If you are using a UITableView or a UICollectionView, in the cellForRowAtIndexPath: method you can dynamically update an imageView placed in a cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    // Configure the cell...
    [self setCell:cell forIndexPAth:indexPath];

    return cell;
}

- (void)setCell:(UITableViewCell *)cell forIndexPAth:(NSIndexPath *)indexPath
{

     __weak UITableViewCell *weakCell = cell;

    // 5. add picture with AFNetworking
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"www.facebook.com/profileImageLocation"]];
    [cell.profileImage setImageWithURLRequest:request
                                        placeholderImage:nil
                                                 success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                                     weakCell.profileImage
                                                     .image = image;

                                                 } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                                                     NSLog(@"bad url? %@", [[request URL] absoluteString]);
                                                 }];
}

Another option will be using a for loop like this:

- (void)addImagesToAllMyImageViews:(NSArray *)images
{
    for (id obj in images) {

        if ([obj isKindOfClass:[UIImageView class]]) {

            UIImageView *imageView = (UIImageView *)obj;

            imageView.image = [UIImage imageNamed:@"someImage.png"];
        }
    }
}

Upvotes: 1

Retro
Retro

Reputation: 4005

I think you can do with tag property, select all ImageView and give them a teg like 777 and

for(id* subview in self.view.subview) {
   if([subview isKindaOfclass:[UIImageView class]] && (subview.tag == 777)) {
      UIImageView* imageView = (UIImageView*)subview;
      imageVIew.image = youImage;
   }
 }

hope this helps you

Upvotes: 0

Related Questions