how to lisent to each button for iphone
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];
开发者_StackOverflow中文版 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
{
}
}
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.");
...
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 {}
精彩评论