2012-02-29 41 views
-2

我想動態生成按鈕。下面的代碼生成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!"); 
} 

回答

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個UIButtons,但應該有到W/E你正在嘗試做一個更好的方法。

+0

完美 - 謝謝。 Obj C對我來說是新的,我試圖找出自動生成類。 – SimonRH 2012-03-01 02:10:42

2

刷上了Objective-C的控制結構 - 尤其是對()循環:

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