1. 程式人生 > >iOS中按鈕根據tag來區分

iOS中按鈕根據tag來區分

- (void) createButton
{
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame = CGRectMake(20, 60, 80, 40);
  
  [button setTitle:@"掃按1" forState:UIControlStateNormal];
  [button setTag:22];
  [self.view addSubview:button];
  
  //[button addTarget:self action:@selector(ClickEvent) forControlEvents:UIControlEventTouchUpInside];
  
  //注意按鈕的回撥事件
  [button addTarget:self action:@selector(ClickEvent:) forControlEvents:UIControlEventTouchUpInside];
  
  
  
  //下面測試多個button呼叫同一個事件,類似Adnroid中的事件類
  UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  button2.frame = CGRectMake(20, 100, 80, 40);
  
  [button2 setTitle:@"按鈕2" forState:UIControlStateNormal];
  
  [self.view addSubview:button2];
  // clickevent include muitle arges
  [button2 addTarget:self action:@selector(ClickEvent:) forControlEvents:UIControlEventTouchUpInside];
  
  [button2 setTag:21];

}
//回撥事件
- (void) ClickEvent
{
  NSLog(@"button click event......");
}

- (void) ClickEvent:(UIButton *) button
{
  NSUInteger BtnTag = [button tag];
  if(BtnTag == 21)
  {
     NSLog(@"\nbutton is:button2");
  }
  else
  {
    NSLog(@"\nbutton is:button1");
  }
 
}