1

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;  
    }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

You might want to tweak that a bit - your first tag would be 0, the default tag for all untagged views. Try viewWithTag:i+100 and tag your pieces 100, 101, 102 ... ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.