我想動態地創建一些UIbutton。並顯示標籤號碼。所以我成功製作了按鈕,點擊了第一個按鈕,標籤顯示「null」,然後點擊第二個按鈕,程序崩潰了。我不確定我的代碼哪部分出錯了。UIbutton和動作問題
這裏是我的代碼:
NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:nil];
for(int i = 0; i < [someArray count]; i++)
{
button = [[UIButton alloc] initWithFrame:CGRectMake(btnX,btnY,btnW,btnH)];
button.tag = i;
[buttonsArray addObject:button];
[[buttonsArray objectAtIndex:i] addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.text = [NSString stringWithFormat:@"Click it"];
[self.view addSubview:button];
btnY = btnY + 120;
}
-(IBAction) buttonPressed:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(@"%@", btn.tag);
}
正確答案...投票 – makboney