如何将一个变量传递给一个UIButton行动

问题描述:

我想一个变量传递到一个UIButton的行动,例如如何将一个变量传递给一个UIButton行动

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

和我的动作功能就像

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

但是,它返回一个语法错误。 有人可以告诉我如何将一个变量传递给UIButton动作吗?

更改它读取:

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

我不知道有关iPhone SDK,但一个按钮动作的目标很可能接收ID(通常命名为发件人)。

- (void) buttonPress:(id)sender; 

在方法调用,发送者应该在你的情况下按钮,让您如它的名字,标签等

我发现做到这一点的唯一方法是读取属性调用动作

前设置一个实例变量,如果需要多个按钮之间进行区分,那么你可以用这样的标签标记您的按钮:

[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 *

您可以使用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

传递变量,我觉得这比从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

您可以设置按钮,并在行动

[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 
    } 
} 

您可以扩展的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 

您可以使用您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]); 
}