我想动态生成按钮。下面的代码生成2个按钮。但是,我怎样才能编写一个循环来生成大量(100或1000)按钮。如何在iOS中动态生成对象?
- (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!");
}
完美 - 谢谢。 Obj C对我来说是新的,我试图找出自动生成类。 – SimonRH 2012-03-01 02:10:42