开发者

problem with selector in iphone?

开发者 https://www.devze.com 2022-12-24 18:58 出处:网络
i am having a ap开发者_StackOverflowplication 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 th

i am having a ap开发者_StackOverflowplication 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...


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.


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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号