-2

Lets say I have 10 buttons. For each button i want to pass some text... e.g. Button 1, My New Button 2, etc....

What I want to do is print this text in NSLog.

Hence I created one method and passed this to button. But I am not getting how can I pass data into it...

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

But I am not getting... any idea how to get this done?

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276

3 Answers3

2

You can associate data with objects as :

Firstly import this class : #import <objc/runtime.h>

Then create a key as

static char * kIndexPathAssociationKeySTR = "associated_string_key";

then associate string as : ** Here you can associate any type of data with button like : NSMutableArray or NSString etcetra**

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

then access it in your method you called on button event as :

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

}

Hope it helps you.

Nishant Tyagi
  • 9,893
  • 3
  • 40
  • 61
2

set tag for the button

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

now compare tag

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

Also you can probably checkout Blocks, extend a uibutton to support blocks (UIButton block equivalent to addTarget:action:forControlEvents: method?).

Community
  • 1
  • 1
Sathya
  • 2,197
  • 4
  • 22
  • 25
-1

Try this,

[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...    
}
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • 3
    This is very wrong, conceptually. Cluttering the accessibility options of the UI? No way... –  Jul 25 '13 at 15:11
  • 1
    @JackyBoy And it doesn't even use jQuery! –  Jul 25 '13 at 16:17