2009-01-16 38 views
10

我有以下代碼:如何將參數傳遞給此函數?

[replyAllBtn addTarget:self.target action:@selector(ReplyAll:) forControlEvents:UIControlEventTouchUpInside]; 

- (void)replyAll:(NSInteger)tid { 
// some code 
} 

我怎麼能傳遞一個參數到ReplyAll功能?

回答

21

replyAll方法應該接受(id)發件人。如果一個UIButton觸發了該事件,那麼相同的UIButton將作爲發送者傳遞。 UIButton有一個屬性「標籤」,你可以附加你自己的自定義數據(很像.net winforms)。

所以,你會鉤住了您的活動:

[replyAllBtn addTarget:self.target action:@selector(ReplyAll:) forControlEvents:UIControlEventTouchUpInside]; 
replyAllBtn.tag=15; 

然後用處理:

(void) ReplyAll:(id)sender{ 
    NSInteger *tid = ((UIControl*)sender).tag; 
    //... 
+0

嘿thanx這正是我想要的...... 添加標籤可以正常工作,但在Controller中定義了replyAll func NSInteger * tid =(* NSInteger)sender.tag; } 給出了一個錯誤說:「在一些會員標籤要求不是一個結構或聯合」 :( – Vijayeta 2009-01-19 07:05:33

+1

感謝清理這件事,羅布。我試圖找出到底我要去完成同樣的行爲Vijayeta正在尋找。@Vijayeta:發件人本身就是按鈕,所以我相信你需要嘗試「((UIControl *)sender).tag;」。注意,你必須用cast括起來,然後才能訪問標籤屬性 – LucasTizma 2009-05-13 20:26:44

1

Cocoa中使用的MVC模型的工作方式不同。基本上,這個想法是,一個按鈕等控件(=視圖)只能讓一個函數知道它被按下了,而不知道這意味着什麼。該功能然後必須知道所有的動態和依賴關係。就你而言,它是必須找到參數的函數。要做到這一點,你會「綁定」其他對象的功能(=控制器)。

我建議你先閱讀一些Cocoa教程,如果你想獲得iPhone編程。

2

選擇器功能通常被定義爲這樣:

- (void) ReplyAll:(id)sender; 

因此,一個動作都不會接收的唯一參數是實際控制調用它。 你可以添加一個屬性到你的控件,可以閱讀的答覆全部

+0

嗨,Thanx的及時回覆,一個疑問,我有,因爲控制是UIButton的一個實例,我怎麼可以添加任何屬性呢? 可能是問題是天真......但我真的不明白。 – Vijayeta 2009-01-17 09:27:37

0

有幾個很好的方法來做到這一點。最常用的兩種方法是讓控制者(接受行動的人)瞭解可能的發件人,或讓發件人自己有一種方法,最終用它來確定正確的行爲。

第一(我的優選的方式,但它很容易爭辯對面)將實施像這樣:

@interface Controller : NSObject { 
    UIButton *_replyToSender; 
    UIButton *_replyToAll; 
} 
- (void)buttonClicked:(id)sender; 
@end 

@implementation Controller 
- (void)buttonClicked:(id)sender { 
    if (sender == _replyToSender) { 
     // reply to sender... 
    } else if (sender == _replyToAll) { 
     // reply to all... 
    } 
} 
@end 

第二種方法將在一種方式來實現,諸如:

typedef enum { 
    ReplyButtonTypeSender = 1, 
    ReplyButtonTypeAll, 
} ReplyButtonType; 

@interface Controller : NSObject { 
} 
- (void)buttonClicked:(id)sender; 
@end 

@interface MyButton : UIButton { 
} 
- (ReplyButtonType)typeOfReply; 
@end 

@implementation Controller 
- (void)buttonClicked:(id)sender { 
    // You aren't actually assured that sender is a MyButton, so the safest thing 
    // to do here is to check that it is one. 
    if ([sender isKindOfClass:[MyButton class]]) { 
     switch ([sender typeOfReply]) { 
      case ReplyButtonTypeSender: 
       // reply to sender... 
       break; 
      case ReplyButtonTypeAll: 
       // reply to all... 
       break; 
     } 
    } 
} 
@end 
2

如果您想發送一個int值,設置按鈕標籤=的你想傳遞的int值。然後你可以訪問按鈕的標籤值來獲得你想要的int。

NSInteger不是一個指針。試試這個

NSInteger tid = sender.tag; 
2

它現在正在工作:D。

{ 
NSInteger tid = [sender tag]; 
}