views:

84

answers:

1
+1  Q: 

For Loop Question?

I'm programming an app for the iPhone. I'm not very good with loops just yet. How do I shorten this code into a for loop?

if(CGRectContainsRect([space1 frame], [box frame])){

  space1.image = [UIImage imageNamed:@"box.png"];
 }
 else if(CGRectContainsRect([space2 frame], [box frame])){

  space2.image = [UIImage imageNamed:@"box.png"];
 }
 else if(CGRectContainsRect([space3 frame], [box frame])){

  space3.image = [UIImage imageNamed:@"box.png"];
 }
 else if(CGRectContainsRect([space4 frame], [box frame])){

  space4.image = [UIImage imageNamed:@"box.png"];
 }
 else if(CGRectContainsRect([space5 frame], [box frame])){

  space5.image = [UIImage imageNamed:@"box.png"];
 }
+6  A: 
NSArray * spaces = [NSArray arrayWithObjects:space1, space2, space3, space4, space5, nil];
for (Space * space in spaces) {
  if (CGRectContainsRect([space frame], [box frame])) {
    space.image = [UIImage imageNamed:@"box.png"];
  }
}
Dave DeLong
2 errors, Spaces undeclared and selector element does not have a valid type
NextRev
@NextRev - check your capitalization.
Dave DeLong
I copied it exactly. Still says Space undeclared
NextRev
@NextRev That's because I have no idea what kind of objects `space1` ... `space5` are, and so I just made up the `Space` class. Change that to whatever type they're supposed to be.
Dave DeLong
Sorry bout that, I'm new to this stuff, they are UIImageViews. I'm actually trying to detect when the user slides a finger across these UIImageViews without lifting the finger, and have code executed as they pass over each UIImageView. Is this something complicated or is there a short line of code like this for loop you provided?
NextRev