I've spend the last several hours working on a loop designed to take items in an array and arrange them as a so to speak "gird" of UIButtons. As far as I've been able to see through testing this code works perfectly.
However, I am new to creating loops and I was wondering if anyone could give me any pointers on how I could make this code cleaner/more efficient for future coding purposes.
I know my question is very similar to Optimize sorting of Array according to Distance (CLLocation), but I'm really hoping to get some tips on a "per case" basis. Thank you for your time.
- (void)myMethod
{
NSArray *array = [[NSArray alloc] initWithObjects:@"Item #1", @"Item #2", @"Item #3", @"Item #4", @"Item #5", @"Item #6", @"Item #7", @"Item #8", nil];
BOOL leftOkay = NO;
BOOL centerOkay = NO;
BOOL rightOkay = NO;
int left = 0;
int center = 1;
int right = 2;
int yOrigin = 0;
int spaceBetweenItems = 5;
UIButton *leftButton;
UIButton *centerButton;
UIButton *rightButton;
for (int i = 0; i < [array count]; i++)
{
if (left < [array count]) {
leftButton = [[UIButton alloc] initWithFrame:CGRectMake(spaceBetweenItems, yOrigin + spaceBetweenItems, 100, 150)];
[leftButton setTitle:[array objectAtIndex:left] forState:UIControlStateNormal];
[leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[leftButton setBackgroundColor:[UIColor cyanColor]];
[myScrollView addSubview:leftButton];
leftOkay = YES;
}
if (center < [array count]) {
centerButton = [[UIButton alloc] initWithFrame:CGRectMake(110, yOrigin + spaceBetweenItems, 100, 150)];
[centerButton setTitle:[array objectAtIndex:center] forState:UIControlStateNormal];
[centerButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[centerButton setBackgroundColor:[UIColor yellowColor]];
[myScrollView addSubview:centerButton];
centerOkay = YES;
}
if (right < [array count]) {
rightButton = [[UIButton alloc] initWithFrame:CGRectMake(215, yOrigin + spaceBetweenItems, 100, 150)];
[rightButton setTitle:[array objectAtIndex:right] forState:UIControlStateNormal];
[rightButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[rightButton setBackgroundColor:[UIColor purpleColor]];
[myScrollView addSubview:rightButton];
rightOkay = YES;
}
if (leftOkay == YES && centerOkay == YES && rightOkay == YES) {
yOrigin = yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2);
leftOkay = NO;
centerOkay = NO;
rightOkay = NO;
}
left = left + 3;
center = center + 3;
right = right + 3;
}
myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2));
}