tags:

views:

423

answers:

2

i am having a application where i am generating the uibuttons dynamically want to use same @selector...Now as sooon as event is generated i wanna check for values and pass it to thtroughthat selector how can i implement this code? can anyone tell me a tutorial sort where buttons are dynamically generated and check for particular button click is depicted? Plz help...

A: 

Try:

[self.button1 addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[self.button2 addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];

- (IBAction)buttonTouchDown:(id)sender
{
  if (sender == self.button1) NSLog(@"Button-1");
  if (sender == self.button2) NSLog(@"Button-2");
}
Kevin Sylvestre
hey thanx but i cant use it it this way.. Actually i am using single selector for multiple buttons and again i am done with the code i just make used of button tags.....thank u...
abhiTouchmagic
+1  A: 

Not sure what do you call "dynamically"... Objective-c objects are always created dynamically. Perhaps you mean situation where you want to create series of very similar buttons with same code? Yes, it is quite a common task. For example in calculator like app, we need ten buttons with digits, why not create them with single block of code ? So:

- (void)makeButtons{
    UIButton * aButton;
    for(int i = 0; i < 10; i++){
        aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        aButton.frame = CGRectMake(0, i*45, 60, 40);
        [aButton addTarget:self action:@selector(digitClick:) forControlEvents:UIControlEventTouchUpInside];
        [aButton setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
        aButton.tag = i;
        [self.view addSubview:aButton];
    }
}

- (void)digitClick:(id)sender{
    UIButton * aButton =(UIButton *)sender;
    NSLog(@"cliced button with title %d",aButton.tag); 
}

we use a tag property to find index of clicked button, it is often used way, but there are some other ways. For example store created buttons in array and then check if sender is equal to one of array elements: ... if ([allButtons objectAtIndex:i] == sender) ...

If you want to pass some data, for example string from each button just create array with these objects and then access it using tag as index.

Vladimir
ya i have implemented this with the use og button tags and tile...so thanx for ur help...
abhiTouchmagic