2010-10-29 92 views
1
NSString *name = @"John"; 

我需要通過上面的變量值,當點擊uibutton。目前,我創建了UIButton的象下面這樣:如何在點擊UI按鈕時將值發送到函數

sendButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)]; 

[sendButton setTitle:@"YES!" forState:UIControlStateNormal]; 

[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside]; 

[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

sendButton.backgroundColor = [UIColor whiteColor]; 

[popoverView addSubview:sendButton]; 

[sendButton release]; 

當我點擊上面的按鈕,它會調用該方法,但我想通過變量(名稱)的功能...

請指引我得到它....

回答

1

您可以創建自定義按鈕的UIButton 的子類,比如,你可以創建爲

性能

在.h文件中

@interface CustomButton : UIButton 
{ 
    NSString *name; 

} 

@property (nonatomic,retain) NSString *name; 
@end 

.m文件

@implementation CustomButton 

@synthesize name; 

- (void)dealloc{ 

    [name release]; 

    [super dealloc]; 
} 

@end 

現在你在哪裏,其中被觸發,你可以使用訪問它的方法創建按鈕

sendButton = [[CustomButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)]; 

[sendButton setTitle:@"YES!" forState:UIControlStateNormal]; 

[sendButton setName:@"John"]; 

[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside]; 

[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

sendButton.backgroundColor = [UIColor whiteColor]; 

[popoverView addSubview:sendButton]; 

[sendButton release]; 

現在的代碼按鈕的屬性名爲

+0

Hi..Thnks您time..is這將參數傳遞給函數 – iPhonegal 2010-10-29 13:23:58

1

雖然你可以繼承UIButton並添加屬性es等等,等等,你最好在popoverView類中命名一個實例變量。 sendAlert方法也可以訪問它。每次需要將數據傳遞給它們時,您都不希望子類化控件。

2

Sherry的答案在技術上是正確的,但是,林不知道它是否是一個潛在的設計模式問題的解決方案。

變量'name'會改變嗎?如果是這樣,它是如何改變(領域,列表選擇..等)?

如果它dosnt改變那麼你應該#define它,如果它確實改變(用戶輸入),那麼你的事件應該看數據源,UI字段或實例變量。

1

你不需要繼承UIButton。

將一個NSString屬性添加到popoverView的類(您正在關注MVC嗎?popoverView應該是一個控制器)。然後在將其添加到子視圖之前,將第一個對象中的NSString分配給popoverView中的NSString。完成了!

您也可以考慮使用通知,如果你要在別的地方在你的應用程序中使用該名稱。

如果您發佈整個代碼,我會修復代碼爲你:)

+0

一個唯一的辦法是不明確以及如果你有多個按鈕需要這樣做呢? – user102008 2011-04-23 01:39:16

相關問題