2010-03-17 20 views
10

如何以編程方式爲按鈕設置標籤?我如何設置和獲取UIButtons的標籤?

我以後要比較的標籤結論

香港專業教育學院試過這種

-(IBAction)buttonPressed:(id)sender{ 
NSLog(@"%d", [sender tag]); 
} 

但只是崩潰的應用程序.... :(

任何其他的想法?

乾杯夥計

山姆

回答

13

你需要轉換爲發送一個UIButton:

-(IBAction)buttonPressed:(id)sender{ 
UIButton *button = (UIButton *)sender; 
NSLog(@"%d", [button tag]); 
} 

編輯:關於消息「無法識別的選擇」 ......

根據您的錯誤信息,這是不能夠調用buttonPressed方法第一個地方。請注意錯誤消息中它正在尋找「buttonPressed」(結尾處沒有冒號),但方法名爲「buttonPressed:」。如果您在代碼中設置按鈕目標,請確保將選擇器設置爲buttonPressed:而不是僅按下按鈕。如果您在IB中設置目標,則xib可能與代碼不同步。

另外,您的原始代碼「[sender tag]」也應該可以工作,但要訪問按鈕特定的屬性,您仍然需要將其轉換爲UIButton。

+0

仍然崩潰... :( –

+0

2010-03-17 16:07:35.322內存[37490:207 *** - [MemoryViewController buttonPressed]:無法識別的選擇發送到實例0x3b08cb0 2010-03-17 16:07:35.324內存[37490:207] ***由於未捕獲的異常'NSInvalidArgumentException',原因:'*** - [MemoryViewController buttonPressed]:無法識別的選擇器發送到實例0x3b08cb0' stack .... –

+1

[button tag] should work。Please see edits to the answer。 – DyingCactus

5

我知道這是一個古老的問題,在其他問題中已經回答了很多次,但是它在谷歌搜索中作爲第二位出現在頂部。所以,這是它爲什麼崩潰的答案。將其更改爲'button.tag'

-(void)myMethod 
{ 
    UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [theButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown]; 

    theButton.tag = i;//or whatever value you want. In my case it was in a forloop 

} 

-(void)buttonPressed:(id)sender 
{ 
    UIButton *button = (UIButton *)sender; 
    NSLog(@"%d", button.tag); 
} 
+0

It works!but it is strange that [button tag] crash!Is not it []更原生的與。notation相比 – sooon

+0

@ sooon:button.tag在內部實現編輯爲[button getTag]和[button setTag:]。由於實際上沒有「標籤」功能,因此崩潰。 – prewett

-1

無需鑄造。這應該工作:

-(IBAction)buttonPressed:(UIButton*)sender 
{ 
NSLog(@"%d", [sender tag]); 
}