Reputation: 3892
So I want to put some UIImageViews into my view. I want them to be put in random places and I need to be able to get the location of each of the random UIImageView later in code.
I would just have 5 UIImageViews and do each one separately, but I may need more or less then 5 at a later point, So a standard, uniform way would be the best approach.
This is the code I'm working with right now:
for (int i=0; i<5; ++i) {
snack = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"03-loopback.png"]];
//snack.frame = CGRectMake(104, 76, 32, 22);
snack.frame = CGRectMake(arc4random()%448, arc4random()%298, 32, 22);
[self.view addSubview:snack];
snackLocation = CGPointMake(snack.center.x, snack.center.y);
}
Upvotes: 0
Views: 525
Reputation: 7643
I think you can use tags:
add in the for loop:
snack.tag=i;//Set the tag for each imageview
then to access to a subview you can loop on each subview of your main view
for (UIView *yourSubView in [self.view subviews]) {
if (yourSubView.tag == YOUR_TAG) {
//Do what you want with the view
break;//jump out the loop
}
}
You can also use this to write less code and access directlty to the frame of your subview:
[self.view viewWithTag:YOUR_TAG].frame=YOUR_FRAME;
Take a look the inspector in IB, each UI element has a property tag that you can set to identify your elements.
Upvotes: 3
Reputation: 15238
Store each UIImageView instance in a NSArray so you can get a hold of them later. Then just use the frame property again to retrieve the position:
for (int i=0; i<5; ++i) {
snack = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"03-loopback.png"]];
snack.frame = CGRectMake(arc4random()%448, arc4random()%298, 32, 22);
[self.snackViews addObject:snack]; //self.snackViews is an NSMutableArray
[self.view addSubview:snack];
}
Later on, you can get all the views from the self.snackViews
array.
Upvotes: 1