How do I convert a series of similar lines into a for loop?
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"];
}
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"];
}
}
精彩评论