2012-04-06 12 views
0

我的故事板中有一個巨大的瘋狂場景,它有36個不同的按鈕,每個按鈕在點擊時意味着不同的東西。我真的不想創建36種不同的方法,所以我怎麼能在按下36個按鈕之一時調用的方法中引用按鈕標題或按鈕名稱。將多個按鈕鏈接到不同作業的一種方法

這可能是一個簡單的問題,但我是新來的iOS和目標C ...

謝謝!

+1

可能重複:http://stackoverflow.com/questions/5858247/ios-one-ibaction-for-multiple-button s – 5StringRyan 2012-04-06 16:25:11

回答

2

給每個按鈕一個唯一的標籤值。在IBAction中,sender.tag告訴你哪個按鈕被點擊。

+0

我使用時sender.tag – 2012-04-06 16:40:20

+0

嗯...嘗試(IBAction爲)the_action得到一個錯誤。我看到一個綠色的外觀錯誤。 – meggar 2012-04-06 17:02:21

+0

還不行::-) – 2012-04-06 17:06:41

1

您設置用於處理按鈕按下的IBAction例程具有sender參數。檢查一下決定。

6

您可以創建一個單一的方法,像這樣:

- (IBAction)buttonTapped:(id)sender{ 

    // The button that was tapped is called "sender" 
    // This will log out the title of the button 

    //NSLog(@"Button: %@", sender.titleLabel.text); 

    //Edit: You need a cast in the above line of code: 

    NSLog(@"Button: %@", ((UIButton *)sender).titleLabel.text); 
} 

然後,您可以使用Interface Builder來連接到所有按鍵。你可以有某種if/else邏輯來測試哪個按鈕被點擊。

您可以檢查titleLabel屬性,或者您可以將IBOutlet指定給每個按鈕並檢查該屬性。

例如:

if([sender isEqual:buttonOutlet1]){ 
    //If this button is attached to buttonOutlet1 
    //do something 
} 

或者,你可以簡單地使用每個按鈕的標籤,而不是擔心網點。

第三種選擇是生成代碼中的按鈕,然後將它們作爲一組按鈕的元素訪問。

第四種選擇是向按鈕添加標籤並檢查函數中按鈕的標籤。

+0

這很有效,但是我不得不爲每個按鈕創建插座。 – 2012-04-06 16:32:45

+0

@JoeBurnett - 或者您可以使用titleLabel或使用數組。 – Moshe 2012-04-06 16:35:49

+0

當我做到這一點...的NSLog(@ 「按鈕:%@」,sender.titleLabel.text); ---我得到這個錯誤...住宅「titleLabel」在類型的對象@JoeBurnett您需要發送者轉換爲UIButton的,因爲它是與類型'id'方法可見「__strong ID」 – 2012-04-06 17:10:41

0

這很簡單,但因爲你是新手,所以這裏有一個答案。 (根據Stanford cs193p課程,2010-2011秋季(這是他們對計算器應用程序所做的))製作一個方法,接收一個參數,即UIButton。 例如:

- (IBAction) someMethodThatDoesSomething:(UIButton *)sender; 

如果根據sender.titleLabel.text
我不知道是否有任何其他的解決辦法陳述然後做。希望這可以幫助!

0
-(IBAction) buttonPress: (id) sender { 
    UIButton *pressedButton = (UIButton *)sender; 
    NSString *buttonTitle = [pressedButton currentTitle]; 
    if ([buttonTitle isEqualToString: @"SomeTitle"]) { 
     //do work for that button. 
    } 
} 

您可以使用各種方法NSString的比較或按下按鈕,過濾器,如果是或交換機處理它通過。

0

- (IBAction爲)myButtonAction:(ID)發送方{

if ([sender tag] == 0) { 
     // do something here 
    } 
    if ([sender tag] == 1) { 
     // Do some think here 
    } 

} 

//換句話說

- (IBAction爲)myButtonAction:(ID)發送方{

 NSLog(@"Button Tag is : %i",[sender tag]); 

    switch ([sender tag]) { 
    case 0: 
     // Do some think here 
     break; 
    case 1: 
     // Do some think here 
     break; 
    default: 
     NSLog(@"Default Message here"); 
     break; 

}

相關問題