tags:

views:

30

answers:

2

i have created 4 dynamic buttons but how to write method on each of them

 for (i = 1; i <= [a1 count]-1; i++)
         {

             NSString *urlE=[a1 objectAtIndex:1];
             NSLog(@"url is %@",urlE);




#pragma mark buttons
             CGRect frame = CGRectMake(curXLoc, 10, 60, 30);
                 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                 button.frame = frame;
             [button setImage:[UIImage imageNamed:@"tab2.png"] forState:UIControlStateNormal];
                 [button setTitle:(NSString *)@"new button" forState:(UIControlState)UIControlStateNormal];
                 [button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
                 curXLoc += (kScrollObjWidth1);   
                 [self.view addSubview:button];


         }



-(void)buttonEvent:(id)sender {
        NSLog(@"new button clicked!!!");
    if (sender == ??)  how to tell button 1 ,2,3,4 
    {


    }


}
+3  A: 

You should give a .tag to each button on creation

             UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
             button.tag = i;  // <-- here
             ...

With this, you could identify the button by .tag.

-(void)buttonEvent:(UIButton*)sender {
        NSLog(@"new button clicked!!!");
        if (sender.tag == 2) {
           NSLog(@"2nd button clicked.");
           ...
KennyTM
wow thanks a lot you saved me :-)
ram
hey but is ther ny other way then tag==2 cause i want to be dynamic lets say i= 10 so it will automatically go upto 10
ram
@ram: what do you mean by "go up to 10"?
KennyTM
A: 

You can specify a separate selector for each button using NSSelectorFromString to dynamically generate selector names.

For example

NSString *selectorName = [NSString stringWithFormat:@"button%dEvent:", i];
[button addTarget:self action:NSSelectorFromString(selectorName) forControlEvents:UIControlEventTouchUpInside];


-(void)button1Event:(UIButton*)sender {}
-(void)button2Event:(UIButton*)sender {}
-(void)button3Event:(UIButton*)sender {}
-(void)button4Event:(UIButton*)sender {}
Steam Trout