1

I want to create a dynamic grid using for loop but I can't. I create demo here but it is not work and I can't understand the logic of this because I'm new in this.

It is important that I have to use for loop no others. So please give me any solutions using for loop. This is in my viewDidLoad method.

int x=5;
int y=5;
int hei=50;
int wid=50;

for (int i=0; i<3; i++) 
{
    for(int j=0;j<3;j++)
    {
        if (i==0 && j==0)
        {
            imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, wid, hei)];
            [imageView1 setImage:[UIImage imageNamed:@"Motocross.png"]];
            [self.view addSubview:imageView1];                        
        }
        else 
        {
            imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(x+wid+5, y+hei+5, wid, hei)];
            [imageView1 setImage:[UIImage imageNamed:@"Motocross.png"]];
            [self.view addSubview:imageView1];
        }

    }   
}

In that I want to create dynamic grid and the size of UIimageView is 50*50 and the space between UIImageView is 5. So in demo I generates only 3*3 grid (same as gallery in mobile).

2 Answers 2

3

please try this code it works for 2*2 grid. And change upon your requirement

    -(void)loadThumbScroll{

    UIButton *button;

    NSUInteger n = [arrimg count];
    int i=0,i1=0;

    while(i<n){
        int yy = 15 +i1*90;
        int j=0;

        //this is for column
        for(j=0; j< 2;j++){

            if (i>=n) break;
            CGRect rect = CGRectMake(15+150*j, yy, 140, 80);
            imageView1 = [[UIImageView alloc]initWithFrame: rect];];
                [imageView1 setImage:[UIImage imageNamed:@"Motocross.png"]];
                    [self.view addSubview:imageView1];   

            i++;

        }
        i1 = i1+1;
    }

    [thumbScrollView setContentSize:CGSizeMake(thumbScrollView.frame.size.width, button.frame.origin.y+button.frame.size.height+20)];

}
Sign up to request clarification or add additional context in comments.

Comments

1

You generate only 3x3 grids because that is the value defined in your loop initialization, if you want a bigger grid just change those value, for instance for a 5x5 grid :

int x=5;
int y=5;
int hei=50;
int wid=50;

for (int i=0; i<5; i++)
{
    for(int j=0;j<5;j++)
    {
        imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake((x+wid)*i, (y+hei)*j, wid, hei)];
        [imageView1 setImage:[UIImage imageNamed:@"Motocross.png"]]
        [self.view addSubview:imageView1];

    }   
}

1 Comment

Thank you! This code is very easy and now i understand the logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.