所以我有一个IBAction连接到IB中的多个按钮我希望在调用另一个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认为它已被按下。
提前谢谢。
答案 0 :(得分: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];
}
}
答案 1 :(得分: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);
}
答案 2 :(得分: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);
}