2010-08-06 68 views
0

我已创建4个动态按钮,但如何在他们每个人的书写方法如何lisent到每个按钮的iPhone

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

你应该给一个.tag每个按钮上创造

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

有了这个,你可以通过.tag识别按钮。

-(void)buttonEvent:(UIButton*)sender { 
     NSLog(@"new button clicked!!!"); 
     if (sender.tag == 2) { 
      NSLog(@"2nd button clicked."); 
      ... 
+0

哇非常感谢你救了我:-) – ram 2010-08-07 01:16:12

+0

哎但其他疗法NY方式则标记== 2,因为我想成为动态可以说,我= 10所以它会自动去吧10 – ram 2010-08-07 01:19:03

+0

@ram:你的意思是“上升到10”? – kennytm 2010-08-07 06:30:44

0

您可以指定使用NSSelectorFromString动态生成选择名称每个按钮单独选择。

例如

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 {} 
相关问题