Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a grid of UIButtons with dynamic values in iOS?

I am trying to create a grid of UIButtons . The row and column values are dynamic.I know how to create a grid .However making it using dynamic values is the problem.

 -(void)makeLayoutWithMinRow:(int)minRow maxRow:(int)maxRow minColumn:(int)minColumn maxColumn:(int)maxColumn {

    NSInteger intLeftMargin = 10; // horizontal offset from the edge of the screen
    NSInteger intTopMargin  = 10; // vertical offset from the edge of the screen
    NSInteger intYSpacing   = 30; // number of pixels between the button origins (vertically)
    NSInteger intXTile;
    NSInteger intYTile;

    NSInteger width;

    width = ((self.layoutView.frame.size.width-(maxColumn * 5))/maxColumn);
    for (int y = minRow; y < maxRow; y++)
    {
        for (int x = minColumn; x < maxColumn; x++)
        {
            intXTile = (x * width) + intLeftMargin;
            intYTile = (y * intYSpacing) + intTopMargin;
            UIButton *buttons[x][y] = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
            //Here I get error : Variable-sized object may not be initialised.

            [self.layoutView addSubview:buttons[x][y]];
        }
    }
}

I did try the option as suggested by Cornelius below to store the button in array.

 sButton = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
 [buttons addObject:sButton]; 

How to add these buttons to view in this case?

for (UIButton *obj in buttons) {
    [self.layoutView addSubview:obj];    //Doesn't work

}
like image 753
icodes Avatar asked Jan 18 '26 14:01

icodes


2 Answers

Here is the one which replaces UICollectionView.I have tried PSTCollectionView and it gives you the expected results. Try this.

You can use PSTCollectionView.

like image 200
Sushil Sharma Avatar answered Jan 21 '26 06:01

Sushil Sharma


Use UICollectionView to create such grid.

Here is a tutorial. For your case, it's UIButton instead of UIImageView in this tutorial.

like image 36
Ashok Avatar answered Jan 21 '26 04:01

Ashok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!