Search code examples
xcodeloopsif-statementuibuttoncgrectmake

Xcode: change row for looping buttons


using the code down below to loop out 200 buttons and wnat the row go down a notch when the row is full. Im guessing there must be a better way because my way dosent work.

When the second and third row begins i onl have one button. No errors just buttons on each other on the last rows.

-(void)viewDidLoad {
int numba=0;
int x=-20;
int y=20;

for(int i = 1; i <= 200; ++i) {


    numba ++;


    if (numba <16) {

        x =x+20;

    } else if (numba >16 && numba <26){
        x=-20;
        x = x + 20;
        y=40;

    } else if (numba >26 && numba <36){
        x=-20;
        x =x+20;
        y=60;

    } else {
        x=-20;
        x =x+20;
        y=80;
    }



    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(x, y, 20, 20);


    NSLog(@"numba = %d",numba);
    NSLog(@"x = %d",x);




    btn.tag = numba;
    [btn setTitle:[NSString stringWithFormat: @"%d", numba] forState:UIControlStateNormal];

    [self.view addSubview:btn];


    }

}


Solution

    1. When you want to create a 2-dimensional grid, it's best to just use nested loops instead of trying to be clever with a single loop.

    2. Don't sprinkle constant numbers all over your code. You can define symbolic constants in a method or function.

    Here's how I'd do it:

    - (void)viewDidLoad {
        static const CGFloat ButtonWidth = 20;
        static const CGFloat ButtonHeight = 20;
        static const CGFloat RowWidth = 320;
    
        int buttonNumber = 0;
    
        for (CGFloat y = 0; buttonNumber < 200; y += ButtonHeight) {
            for (CGFloat x = 0; buttonNumber < 200 && x + ButtonWidth <= RowWidth; x += ButtonWidth) {
                ++buttonNumber;
                UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                button.frame = CGRectMake(x, y, ButtonWidth, ButtonHeight);
                button.tag = buttonNumber;
                [button setTtle:[NSString stringWithFormat:@"%d", buttonNumber] forState:UIControlStateNormal];
                [self.view addSubview:button];
            }
        }
    }