2009-02-04 253 views
15

我想一個變量傳遞到一個UIButton的行動,例如如何將一個變量傳遞給一個UIButton行動

NSString *[email protected]"one"; 
[downbutton addTarget:self action:@selector(action1:string) 
    forControlEvents:UIControlEventTouchUpInside]; 

和我的動作功能就像

-(void) action1:(NSString *)string{ 
} 

但是,它返回一個語法錯誤。 有人可以告訴我如何將一個變量傳遞給UIButton動作嗎?

回答

21

更改它讀取:

[downbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside]; 

我不知道有關iPhone SDK,但一個按鈕動作的目標很可能接收ID(通常命名爲發件人)。

- (void) buttonPress:(id)sender; 

在方法調用,發送者應該在你的情況下按鈕,讓您如它的名字,標籤等

1

我發現做到這一點的唯一方法是讀取屬性調用動作

18

前設置一個實例變量,如果需要多個按鈕之間進行區分,那麼你可以用這樣的標籤標記您的按鈕:

[downbutton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside]; 
downButton.tag = 15; 

在你一個ction委託方法你就可以根據其預先設定的標籤處理每個按鈕:

(void) buttonPress:(id)sender { 
    NSInteger tid = ((UIControl *) sender).tag; 
    if (tid == 15) { 
     // deal with downButton event here .. 
    } 
    //... 
} 

UPDATE:sender.tag應該是NSInteger代替NSInteger *

6

您可以使用associative references任意數據添加到您的的UIButton:

static char myDataKey; 
... 
UIButton *myButton = ... 
NSString *myData = @"This could be any object type"; 
objc_setAssociatedObject (myButton, &myDataKey, myData, 
    OBJC_ASSOCIATION_RETAIN); 

對於政策領域(OBJC_ASSOCIATION_RETAIN)指定的情況下,適當的策略。 對動作的委託方法:

(void) buttonPress:(id)sender { 
    NSString *myData = 
    (NSString *)objc_getAssociatedObject(sender, &myDataKey); 
    ... 
} 
+0

這應該是被接受爲正確答案。 注意,這需要以下輸入: #進口 此外,鏈路斷開時:如2016年11月的,該文檔是: https://developer.apple.com/ reference/objectivec/1657527-objective_c_runtime – Gabriel 2016-11-26 18:17:32

5

傳遞變量,我覺得這比從leviatan的回答標籤更直接的另一種方法是通過在accessibilityHint的字符串。例如:

button.accessibilityHint = [user objectId]; 
在按鈕的操作方法

然後:

-(void) someAction:(id) sender { 
    UIButton *temp = (UIButton*) sender; 
    NSString *variable = temp.accessibilityHint; 
    // anything you want to do with this variable 
} 
+0

getting(null)...請建議我獲取確切的字符串。 – 2016-05-12 12:32:59

0

您可以設置按鈕,並在行動

[btnHome addTarget:self action:@selector(btnMenuClicked:)  forControlEvents:UIControlEventTouchUpInside]; 
        btnHome.userInteractionEnabled = YES; 
        btnHome.tag = 123; 

從發件人訪問它在所謂的標籤功能

-(void)btnMenuClicked:(id)sender 
{ 
[sender tag]; 

    if ([sender tag] == 123) { 
     // Do Anything 
    } 
} 
1

您可以擴展的UIButton並添加自定義屬性

//UIButtonDictionary.h 
#import <UIKit/UIKit.h> 

@interface UIButtonDictionary : UIButton 

@property(nonatomic, strong) NSMutableDictionary* attributes; 

@end 

//UIButtonDictionary.m 
#import "UIButtonDictionary.h" 

@implementation UIButtonDictionary 
@synthesize attributes; 

@end 
0

您可以使用您dot'n使用UIControlStates的字符串:

NSString *[email protected]"one"; 
[downbutton setTitle:string forState:UIControlStateApplication]; 
[downbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside]; 

和行動功能:

-(void)action1:(UIButton*)sender{ 
    NSLog(@"My string: %@",[sender titleForState:UIControlStateApplication]); 
} 
相關問題