用数组创建视图

时间:2011-10-26 07:20:00

标签: objective-c arrays xcode

我想以编程方式创建视图,Matrix:10X10 = 100个视图。我创建了IB,但它必须用Xcode编程。我怎么能这样做?

对于一个视图创建此视图,对于10X10视图我不知道。我怎样才能做所有观点;

UIView *tempView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 660, 60, 60)];
                    [self.view addSubview:tempView1];
                    rd = 0;
                    gr = 0.5;
                    bl =0;           
                    tempView1.backgroundColor = [UIColor colorWithRed:rd green:gr blue:bl alpha:1.0];

2 个答案:

答案 0 :(得分:3)

这应该适合你:

for (int i = 0; i < amountOfViewsHorizontally; i++)
{
    for (int j = 0; j < amountOfViewsVertically; j++) 
    {
        UIView *someView = [[UIView alloc] initWithFrame:CGRectMake((i*widthOfView), (j*heightOfView), widthOfView, heightOfView)];
        rd = 0;
        gr = 0.5;
        bl =0;          
        someView.backgroundColor = [UIColor colorWithRed:rd green:gr blue:bl alpha:1.0];

        UILabel *someLabel = [[UILabel alloc] init];
        someLabel.frame = CGRectMake(0,0,50,20); //this will add a label in all the upperleft corners (point(0,0)) of every view with width 50 and height 20.
        [someView addSubView:someLabel];

        //[someViewArray addObject:someView]; //add view to an array
        [self.view addSubview:someView];
    }
}

您可能希望将它们放入某种数组中,以便稍后可以访问它们。


如果您希望将像UILabel这样的组件添加到这些视图中。您必须使用这些视图的实习坐标系。

答案 1 :(得分:1)

有关动态更详细的布局,行,高度的示例,请查看my article here。它显示了如何根据大小和屏幕大小动态布局框,以及动态重新排序的工作原理。

有关详细信息,请参阅文章,但关键方法是......

- (void) layoutBoxesWithRowCount:(NSInteger)rowCount {
  double xPos = kBoxSpacer;
  double yPos = kBoxSpacer;
  int boxCount = 0;

  for(LOBox *box in boxes) {
    CGRect frame = [box frame];
    frame.origin.x = xPos;
    frame.origin.y = yPos;
    [box setFrame:frame];

    xPos += kBoxDimension + kBoxSpacer;
    boxCount++;

    if(boxCount == rowCount) {
        boxCount = 0;
        xPos = kBoxSpacer;
        yPos += kBoxDimension + kBoxSpacer;
    }
  }
}

完整记录here.