如何在iOS中动态生成对象?

时间:2012-02-29 21:36:33

标签: objective-c ios cocoa-touch

我想动态生成按钮。下面的代码生成2个按钮。但是我怎样才能编写一个循环来生成批量(100或1000)按钮。

- (void)viewDidLoad
{
//allocate the view
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

//set the view's background color
self.view.backgroundColor = [UIColor whiteColor];

//create the buttons
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

//set the position of the button
button.frame = CGRectMake(100, 170, 100, 30);
button1.frame = CGRectMake(200, 170, 100, 30);

//set the button's title
[button setTitle:@"Click Me!" forState:UIControlStateNormal];
[button1 setTitle:@"Click!" forState:UIControlStateNormal];

//listen for clicks
[button addTarget:self action:@selector(buttonPressed)
 forControlEvents:UIControlEventTouchUpInside];
[button1 addTarget:self action:@selector(buttonPressed)
 forControlEvents:UIControlEventTouchUpInside];

//add the button to the view
[self.view addSubview:button];
[self.view addSubview:button1];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)buttonPressed {
NSLog(@"Button Pressed!");
}

2 个答案:

答案 0 :(得分:6)

我真的很震惊,你设法在不知道如何进行for循环的情况下完成那里的代码。

除此之外,不要在viewDidLoad中执行此操作。

//allocate the view
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

//set the view's background color
self.view.backgroundColor = [UIColor whiteColor];

UIViewController加载自己的视图,你在这里覆盖它是没有正当理由的。

-(void)viewDidLoad {

    [super viewDidLoad];

    for(int i = 0; i < 1000; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setFrame:CGRectMake(100 + i, 170 + i, 100, 30)];

        [button setTitle:@"Click Me!" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

        [[self view] addSubview:button];
    }
}

-(void)buttonPressed {
    NSLog(@"Button Pressed!");
}

注意:请不要这样做......我不知道为什么你会想要1000个UIButton,但是你应该有更好的方法来实现这个目标。

答案 1 :(得分:2)

刷上objective-c控制结构 - 特别是for()循环:

for (int i ; i < someLargeNumber; i++) {
   ... Make buttons here ...
}