2011-07-27 51 views
1

我想動態地創建一些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); 

}

回答

1

這是因爲tagNSInteger和你正在做的

NSLog(@"%@", btn.tag); 

您必須使用%ld作爲格式說明符。做

NSLog(@"%ld", btn.tag); 
+0

正確答案...投票 – makboney

0

更改代碼 的NSLog(@ 「%@」,self.but.tag); 或 NSLog(@「%@」,self.but.tag.me)