我想使用for循环创建一个动态网格,但我不能。我在这里创建了demo,但它不起作用,我无法理解这个的逻辑,因为我是新手。
重要的是我必须使用for循环而不是其他人。所以请给我任何使用for循环的解决方案。这是在我的viewDidLoad方法中。
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];
}
}
}
因为我想创建动态网格,UIimageView的大小为50 * 50,UIImageView之间的空间为5.因此在演示中我只生成3 * 3网格(与移动中的库相同)。
答案 0 :(得分:2)
请尝试此代码,它适用于2 * 2网格。并根据您的要求进行更改
-(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)];
}
答案 1 :(得分:1)
您只生成3x3网格,因为这是循环初始化中定义的值,如果您想要更大的网格,只需更改这些值,例如5x5网格:
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];
}
}