从单个方法实例化一定数量的唯一对象

时间:2010-11-04 18:58:45

标签: iphone objective-c ipad ios factory-pattern

这是我从来没有能够让我的大脑得到的东西......

假设我正在构建一个8 UIViews宽8个UIViews高的网格。它可以通过任何x,y集合。它不一定是8 x 8.让我们只是随意而且坚持现在。

这个init方法(UIView的子类的一部分)生成一行8 UIViews宽:

    - (id)initWithFrame:(CGRect)frame {

if ((self = [super initWithFrame:frame])) {

    int x = 1;
    int y = 1;

    //row 01
    UIView* row01Square01 = [[UIView alloc] initWithFrame:CGRectMake((0*x), (0*y), x, y)];
    [self addSubview:row01Square01];

    UIView* row01Square02 = [[UIView alloc] initWithFrame:CGRectMake((1*x), (0*y), x, y)];
    [self addSubview:row01Square02];

    UIView* row01Square03 = [[UIView alloc] initWithFrame:CGRectMake((2*x), (0*y), x, y)];
    [self addSubview:row01Square03];

    UIView* row01Square04 = [[UIView alloc] initWithFrame:CGRectMake((3*x), (0*y), x, y)];
    [self addSubview:row01Square04];

    UIView* row01Square05 = [[UIView alloc] initWithFrame:CGRectMake((4*x), (0*y), x, y)];
    [self addSubview:row01Square05];

    UIView* row01Square06 = [[UIView alloc] initWithFrame:CGRectMake((5*x), (0*y), x, y)];
    [self addSubview:row01Square06];

    UIView* row01Square07 = [[UIView alloc] initWithFrame:CGRectMake((6*x), (0*y), x, y)];
    [self addSubview:row01Square07];

    UIView* row01Square08 = [[UIView alloc] initWithFrame:CGRectMake((7*x), (0*y), x, y)];
    [self addSubview:row01Square08];
}

return self;

}

是否有可能编写一个可以使用该代码的方法(当然还有修改)来生成后续的7行UIViews?更好的是,是否可以使用1行生成所有64个UI视图?

我已尝试使用for,while,do循环,但我承认,无论你是否可以将字符串作为参数传递给init方法,我都完全迷失了。

提前感谢您对此的任何见解。

2 个答案:

答案 0 :(得分:2)

你的意思是:

for (int i=0;i<8;i++) {
    UIView* square = [[UIView alloc] initWithFrame:CGRectMake((i*x), (0*y), x, y)];
    [self addSubview:square];
    }

或(对于所有行):

for(int r=0;r<8;r++) {
    for (int i=0;i<8;i++) {
        UIView* square = [[UIView alloc] initWithFrame:CGRectMake((i*x), (r*y), x, y)];
        [self addSubview:square];
        }
    }

答案 1 :(得分:1)

int numberOfRows = 8;
int numberOfColumns = 8;

for (int j = 0; j<numberOfRows;j++){
    for (int i=0;i<numberOfColumns;i++) {
        UIView* square = [[UIView alloc] initWithFrame:CGRectMake((i*x), (j*y), x, y)];
        [self addSubview:square];
    }
}