-2

假设我有 10 个按钮。对于每个按钮,我想传递一些文本……例如按钮 1、我的新按钮 2 等……

我想要做的是在 NSLog 中打印此文本。

因此,我创建了一个方法并将其传递给按钮。但我不知道如何将数据传递给它......

[myButton addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)btnSelected:(id)sender {
    NSLog(@"btnSelected data is %@", sender);
    // I want to print some text for respective button here...    
}

但我没有得到......知道如何完成这项工作吗?

4

3 回答 3

2

您可以将数据与对象关联为:

首先导入这个类:#import <objc/runtime.h>

然后创建一个密钥

static char * kIndexPathAssociationKeySTR = "associated_string_key";

然后将字符串关联为:**在这里您可以将任何类型的数据与按钮关联,例如:NSMutableArray 或 NSString 等**

NSString *myAttachedValue = @"This is the info I am associating with button";
objc_setAssociatedObject(self.testBtn,
                         kIndexPathAssociationKeySTR,
                         myAttachedValue,
                         OBJC_ASSOCIATION_RETAIN);

然后在您调用按钮事件的方法中访问它:

- (IBAction)btnTouched:(UIButton *)sender {
    NSString *valueIs = (NSString *)objc_getAssociatedObject(self.testBtn, kIndexPathAssociationKeySTR);
    NSLog(@"value is : %@",valueIs);

}

希望它可以帮助你。

于 2013-07-25T12:49:39.563 回答
2

为按钮设置标签

[myButton addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
myButton.tag = 1;

现在比较标签

-(IBAction)btnSelected:(id)sender {
    UIButton *button = (UIButton *)
    if(button.tag == 1) { //do button 1 stuff
        NSLog(@"btnSelected data is %@", sender);
    }
}

您也可以检查块,扩展 uibutton 以支持块(UIButton 块相当于 addTarget:action:forControlEvents: 方法?)。

于 2013-07-25T12:50:23.317 回答
-1

尝试这个,

[myButton setAccessibilityValue:@"Some text"];
[myButton addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)btnSelected:(id)sender {
    NSLog(@"btnSelected data is %@", [sender accessibilityValue];);
    // I want to print some text for respective button here...    
}
于 2013-07-25T12:46:12.077 回答