DeZigny
DeZigny

Reputation: 1953

Access many UIImageView in a for loop

I have 5 UIImageView in a UIView, and I have named the UIImageView as follows:

@property (retain, nonatomic) IBOutlet UIImageView *imgPic1;
@property (retain, nonatomic) IBOutlet UIImageView *imgPic2;
@property (retain, nonatomic) IBOutlet UIImageView *imgPic3;
@property (retain, nonatomic) IBOutlet UIImageView *imgPic4;
@property (retain, nonatomic) IBOutlet UIImageView *imgPic5;

Let's say all UIImageViews are filled with an images, and the user can delete any UIImageView in runtime, I want to know how can I achieve the following scenario?

I want an intelligent loop so if the user delete imgPic3, the imgPic4 image will be moved to imgPic3, and imgPic5 will move to imgPic4, and imgPic5 assign to nil

imgPic3.img = imgPic4.img;
imgPic4.img = imgPic5.img;
imgPic5.img = nil;

I can hard code the 5 logical scenarios for each UIImageView if got deleted, but I want to do it in an intelligent way so it will work even if I have 100 UIImageViews.

Upvotes: 0

Views: 265

Answers (1)

jrtc27
jrtc27

Reputation: 8526

Use an NSMutableArray to contain the 5 UIImageView pointers. Then when image view x is removed, do:

for (int i = imgViewNumber; i < [myImageViewArray count]-1; i++) {
    [[myImageViewArray objectAtIndex:i] setImage:[[myImageViewArray objectAtIndex:i+1] image]];
}
[[myImageViewArray lastObject] setImage:nil];

Edit:
To add your UIImageViews to the array:

  1. Don't have each one defined as a property nor an iVar - only have a retained property for the array.
  2. Use a for (int i = 0; i < numImageViews; i++) loop to add all of your image views, and at the same time as calling addSubview:, call [myImageViewArray addObject:imageView].
  3. Then if you want to set the image for a particular image view, call [[myImageViewArray objectAtIndex:imageViewNumber] setImage:image] (bear in mind that for image view 1, imageViewNumber should be 0)

Hope this is now clear

Upvotes: 1

Related Questions