如何以編程方式爲按鈕設置標籤?我如何設置和獲取UIButtons的標籤?
我以後要比較的標籤結論
香港專業教育學院試過這種
-(IBAction)buttonPressed:(id)sender{
NSLog(@"%d", [sender tag]);
}
但只是崩潰的應用程序.... :(
任何其他的想法?
乾杯夥計
山姆
如何以編程方式爲按鈕設置標籤?我如何設置和獲取UIButtons的標籤?
我以後要比較的標籤結論
香港專業教育學院試過這種
-(IBAction)buttonPressed:(id)sender{
NSLog(@"%d", [sender tag]);
}
但只是崩潰的應用程序.... :(
任何其他的想法?
乾杯夥計
山姆
你需要轉換爲發送一個UIButton:
-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", [button tag]);
}
編輯:關於消息「無法識別的選擇」 ......
根據您的錯誤信息,這是不能夠調用buttonPressed方法第一個地方。請注意錯誤消息中它正在尋找「buttonPressed」(結尾處沒有冒號),但方法名爲「buttonPressed:」。如果您在代碼中設置按鈕目標,請確保將選擇器設置爲buttonPressed:而不是僅按下按鈕。如果您在IB中設置目標,則xib可能與代碼不同步。
另外,您的原始代碼「[sender tag]」也應該可以工作,但要訪問按鈕特定的屬性,您仍然需要將其轉換爲UIButton。
我知道這是一個古老的問題,在其他問題中已經回答了很多次,但是它在谷歌搜索中作爲第二位出現在頂部。所以,這是它爲什麼崩潰的答案。將其更改爲'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);
}
無需鑄造。這應該工作:
-(IBAction)buttonPressed:(UIButton*)sender
{
NSLog(@"%d", [sender tag]);
}
仍然崩潰... :( –
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 .... –
[button tag] should work。Please see edits to the answer。 – DyingCactus