如何在没有大量重复代码的情况下创建45个图像视图?

时间:2013-12-25 00:44:48

标签: ios objective-c loops uiimageview

我需要在表单上创建45个50x50像素的图像。这是第一个8.我计划稍后将图像加载到它们中。使用循环有更好的方法吗?当我加载图像时,下面的代码工作正常。我只是想知道是否有更好的方法来创建所有45。

UIView * wview1;
UIView * wview2;
UIView * wview3;
UIView * wview4;
UIView * wview5;
UIView * wview6;
UIView * wview7;
UIView * wview8;    
wview1 = [[UIView alloc] initWithFrame:CGRectMake(10, 20, 50, 50)];
wview2 = [[UIView alloc] initWithFrame:CGRectMake(70, 20, 50, 50)];
wview3 = [[UIView alloc] initWithFrame:CGRectMake(130, 20, 50, 50)];
wview4 = [[UIView alloc] initWithFrame:CGRectMake(200, 20, 50, 50)];
wview5 = [[UIView alloc] initWithFrame:CGRectMake(270, 20, 50, 50)];
wview6 = [[UIView alloc] initWithFrame:CGRectMake(340, 20, 50, 50)];
wview7 = [[UIView alloc] initWithFrame:CGRectMake(410, 20, 50, 50)];
wview8 = [[UIView alloc] initWithFrame:CGRectMake(480, 20, 50, 50)];
wview1.tag = 1;
wview2.tag = 2;
wview3.tag = 3;
wview4.tag = 4;
wview5.tag = 5;
wview6.tag = 6;
wview7.tag = 7;
wview8.tag = 8;
[self.view addSubview:wview1];
[self.view addSubview:wview2];
[self.view addSubview:wview3];
[self.view addSubview:wview4];
[self.view addSubview:wview5];
[self.view addSubview:wview6];
[self.view addSubview:wview7];
[self.view addSubview:wview8];

1 个答案:

答案 0 :(得分:4)

绝对!

for (int i=0; i++; i<45)
{
    UIView *wview;   
    wview = [[UIView alloc] initWithFrame:CGRectMake(10 + 60*i, 20, 50, 50)];
    wview.tag = i+1;
    [self.view addSubview:wview];
}

应该做的工作。