Edward Jackson Edward Jackson - 2 months ago 18
Objective-C Question

How to create views as a grid(such as 9*9 grid, 15*15 grid) by using for loops in Objective-C

I am trying to draw a 15*15 grid in Objective-C. The grid colour is blue which is like making the board of the "Snake" game in NOKIA.

I've tried using the for loop to create subviews but it seems not working, I looked over the internet and most of them are using UIImageView to make the grid, is there any solution for making a 15*15 grid with for loop or I have to use the

UIImageView
method?

- (void)viewDidLoad {
[super viewDidLoad];

int i;
int row = 0;
int col = 0;
int firstColor=0;

if ([[UIDevice currentDevice] userInterfaceIdiom]== UIUserInterfaceIdiomPhone){
cellWidth = 23;
CellHeight= cellWidth;
topY=230-4*CellHeight;
leftX=110-4*cellWidth;
}else{

cellWidth=46;
CellHeight=cellWidth;
topY=500-4*CellHeight;
leftX=384-4*cellWidth;
}


UIView *viewA = [[UIView alloc]initWithFrame:CGRectMake(0, 30, 414, 434)];
viewA.backgroundColor = [UIColor blackColor];
[self.view addSubview:viewA];


for (int row = 0; row < rows; row = row++ ){
for(int r = 0; r <= 414; r = r + 23){
UIView *viewB = [[UIView alloc]initWithFrame:CGRectMake(r,5,23,23)];
viewB.backgroundColor = [UIColor blueColor];

[viewA addSubview:viewB];}}





col=col+1;
firstColor=1-firstColor;
if (col>18){
row=row+1;
firstColor=1-firstColor;
col=0;
}

Answer

One way is to use bezierPath for drawing the custom view. If you need 3*3 grid layout, you need 9 bezier paths!!!!

YOu can achieve this kind of result by using bezier path: enter image description here

YOu can even enter the rows/cols you need:

declare the properties in your view .h file:

   @property (assign) int row;
   @property (assign) int col;

and you can call the view from your view controller using:

-(void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
    testView *tv = [[testView alloc]initWithFrame:CGRectMake(30, 50, 100, 100)];

    tv.row = 3;
    tv.col = 4;

    [self.view addSubview:tv];
}

Here I assumed grid cell size as 20x20

-(void)drawRect:(CGRect)frame {

    int x = 0, y = 0;

        for (int i = 1; i <= _row*_col; i++) {

            UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(CGRectGetMinX(frame) + x + 27, CGRectGetMinY(frame) + y + 13, 20, 20)];

            [UIColor.grayColor setFill];
            [rectanglePath fill];
            [UIColor.blackColor setStroke];
            rectanglePath.lineWidth = 1;
            [rectanglePath stroke];

            x = x + 20;

            if (i%_row == 0) {
                x = 0;
                y = y + 20;
            }

        }
}

You can playaround with the grid colors too!!!

Comments