1

所以我有一个连接到 IB 中的多个按钮的 IBAction 我希望在调用另一个 IBAction 时触发此操作我还希望它能够将第二个操作中的 int 识别为 [sender tag]。

// viewController.m

-(IBAction)buttonPress {

 int getInter  = [sender tag]; 
 UIView *tmpView = [self.view viewWithTag:getInter];
 NSString *title = [(UIButton *)sender currentTitle]; 

}

然后我有另一个需要调用 buttonPress 的操作。

 -(IBAction)secondButtonPress {
  int varInt = 1
  [self buttonPress: nil] <--- How do I pass varInt that buttonPress would recognise as a sender Tag here?

 }

我意识到我可以像这样创建按钮并在 secondButtonPress 中复制代码,但这似乎很混乱......

 UIButton *tmpButton2 = (UIButton *)[self.view viewWithTag:varInt];

所以问题是,有没有办法让 buttonPress 认为它​​已被按下并传递一个变量作为该操作的发送者标签。以某种方式以编程方式欺骗 buttonPress 认为它​​已被按下。

先感谢您。

4

3 回答 3

2

我最终将它连接到同一个 IBAction 并运行一个 if 语句以在调用该标记时执行某些操作。

现在看起来很简单!

-(IBAction)buttonPress {

 int getInter  = [sender tag]; 

   if ([sender tag] == 2) {
    //Do something just for that button.
   }

   else
   {
    UIView *tmpView = [self.view viewWithTag:getInter];
    NSString *title = [(UIButton *)sender currentTitle]; 
   }
}
于 2013-08-12T14:28:43.000 回答
1
UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
[btn1 setTitle:@"Button 1" forState:UIControlStateNormal];
btn1.tag = 1;
[btn1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];

UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 20, 20)];
[btn2 setTitle:@"Button 2" forState:UIControlStateNormal];
btn2.tag = 2;
[btn2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];

UIButton *btn3 = [[UIButton alloc] initWithFrame:CGRectMake(10, 90, 20, 20)];
[btn3 setTitle:@"Button 3" forState:UIControlStateNormal];
btn3.tag = 3;
[btn3 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn3];

编写如下按钮单击方法并在其中获取按钮标签..

-(IBAction)buttonClick:(id)sender {
    UIButton *btn = (UIButton *) sender;
    NSLog(@"%d",btn.tag);
}
于 2013-08-08T11:07:39.413 回答
0

只需在 initWithNibName 方法中设置标签。跟着样本看看对你有没有帮助!!

@property(nonatomic,strong)IBOutlet UIButton *btn1;
@property(nonatomic,strong)IBOutlet UIButton *btn2;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

       // Set the Tag
        self.btn1.tag=1;
        self.btn1.tag=2;

    }
    return self;
}

-(IBAction)selectedButtonClick:(id)sender {
    UIButton *btn = (UIButton *) sender;
    NSLog(@"selectedButton%d",btn.tag);
}
于 2013-08-08T11:47:08.067 回答