簡體   English   中英

如何設置和獲取UIButtons的標簽?

[英]How do I set and get UIButtons' tag?

如何以編程方式為按鈕設置標記?

我后來想要與標簽進行比較得出結論

我試過這個

-(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:而不僅僅是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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM