2010-11-14 70 views
0

嗨我有多個UIButtons(foobar),並按下時,每個調用不同的實例方法(doSomethingFoodoSomethingBar)。以下是我使用的代碼:如何在objective-c實例方法中傳遞字符串?

CGRect fooImageRect = CGRectMake(38.0f, 192.0f, 130.0f, 25.0f); 
    UIButton *buttonFoo = [[UIButton alloc] init]; 
    buttonFoo.frame = fooImageRect; 
    [buttonFoo setImage:[UIImage imageNamed:@"button_foo_130x25.png"] forState:UIControlStateNormal]; 
    [buttonFoo addTarget:self action:@selector(doSomethingFoo:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:buttonFoo]; 
    [buttonFoo release]; 

CGRect barImageRect = CGRectMake(172.0f, 192.0f, 130.0f, 25.0f); 
    UIButton *buttonBar = [[UIButton alloc] init]; 
    buttonBar.frame = barImageRect; 
    [buttonBar setImage:[UIImage imageNamed:@"button_bar_130x25.png"] forState:UIControlStateNormal]; 
    [buttonBar addTarget:self action:@selector(doSomethingBar:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:buttonBar]; 
    [buttonBar release]; 

和實例方法doSomethingFoodoSomethingBar

-(void)doSomethingFoo:(id) sender { 
    // code doing something with a NSString having value 'foo' 
} 

    -(void)doSomethingBar:(id) sender { 
     // same code doing something with a NSString having value 'bar' 
} 

我所試圖做的是建立一個單一的方法(doSomething),我可以調用當任按鈕,並將它傳遞給我將在方法中引用的字符串(值'foo'或'bar')。我正在努力處理語法。

回答

0

您可以使用相同的方法處理這兩個按鈕,但不能選擇發送的參數。動作選擇器必須是下列形式之一:

- (void)action 
- (void)action:(id)sender 
- (void)action:(id)sender forEvent:(UIEvent *)event 

哪裏sender是發送該消息的控制。因此,您可以通過檢查sender來判斷哪個按鈕發送了該消息。在直接進行檢查的可能性是設置UIButton的標籤屬性時,您可以使用一些衆所周知的值(一個#define或其他常量)來創建該屬性,然後在您的操作方法中檢查該屬性。

0

只是讓所謂的按鈕名稱一個NSString伊娃和寫像這樣的方法:

// first set buttonTitle: 
self.buttonTitle = @"foo"; //for buttonfoo 
self.buttonTitle = @"bar", // for buttonbar 




-(void)doSomething:(id) sender { 
NSString *title = self.buttonTitle; 
} 
相關問題