以编程方式创建多个视图

Creating multiple views programmatically

你好我想问一下如何以编程方式创建多个视图并将它们显示在屏幕上,我试过了但是缺少一些东西。

int x,y;

x= 0;
y=50;

for (int i=0; i<4; i++)
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)];

view.backgroundColor = [UIColor redColor];


[self.view addSubview: view];

    y+=40;
} 
int x,y;
x= 0;
y=50;

for (int i=0; i<4; i++)
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)];

    view.backgroundColor = [UIColor redColor];
    view.layer.cornerRadius = 5.0f;
    [self.view addSubview: view];
    y+=140; //y for next view should be height of previous view and margin between view 
} 
  int x,y;

  x= 0;
  y=50
   for (int i=0; i<4; i++)
   {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 30, 30)];

    view.backgroundColor = [UIColor redColor];
     y+=40;

    [self.view addSubview: view];    
  }
int x,y,paddingX,widthOfView,HeightOfView;

x= 0;
y=50;
paddingX = 10;
widthOfView = 100;
HeightOfView = 100;

for (int i=0; i<4; i++){
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, widthOfView, HeightOfView)];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview: view];

    y+= widthOfView + paddingX;
}

以下代码可能对您有所帮助。