Reputation:
in the if
statement below how could i make piece1's name be dynamic so that it checks for other pieces also which are piece1, piece2, ...piece5.
I would have to make it look like something like [@"piece%d",i] I'm just not sure what the correct way of writing this would be since i'm just starting with iOS.
for (int i = 0; i < 6; i++) {
if(CGRectContainsPoint([piece1 frame], location)){
piece1.center = location;
}
}
Upvotes: 1
Views: 136
Reputation: 38475
Something like this :
for (int i = 0; i < 6; i++) {
// Create a selector to get the piece
NSString *selectorName = [NSString stringWithFormat:@"piece%d", i];
SEL selector = NSSelectorFromString(selectorName);
UIView *peice = [self performSelector:selector];
// Now do your test
if(CGRectContainsPoint([piece frame], location)){
piece1.center = location;
}
}
The key bits are NSSelectorFromString
to turn a string into a selector and performSelector:
to get the object matching it.
Upvotes: 1
Reputation: 21805
First add tags to your imageView when initializing them then change your code to this
for (int i = 0; i < 6; i++) {
UIImageView *piece = (UIImageView *)[self.view viewWithTag:i] ;
if(CGRectContainsPoint([piece frame], location)){
piece.center = location;
}
}
make sure your tag matches the value that will be in the loop i values.
Upvotes: 0