I want to generate buttons dynamically. The code below generates 2 buttons. But how can I write a loop to generate lots (100 or 1000) buttons.
- (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!");
}
I am actually stunned that you managed to pull off that code that you have there without knowing how to do a for loop.
Beyond that, dont ever do this in viewDidLoad.
The UIViewController loads its own view, you override it here for no real reason.
Note: please dont ever do this… I have no idea why you would want 1000 UIButtons, but there should be a much better approach to w/e you are trying to do.