第一种方法:根据传入函数的参数对象的tag属性区分
比如 多个按钮执行同一个方法,但是不同的方法执行时,里面的逻辑又不一样 那就得加以区分 这时可以用tag来区别
//再新建一个Button
UIButton * button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.frame = CGRectMake(20, 60, 280, 30);
button2.tag = 2;
button2.backgroundColor = [UIColor redColor];
[button2 setTitle:@"点我2" forState:UIControlStateNormal];
//此action中得click:是代表有参数的click方法
[button2 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
//自定义按钮 UIButtonTypeCustom
UIButton * button3 = [UIButton buttonWithType:UIButtonTypeCustom];
button3.frame = CGRectMake(20, 100, 31, 30);
[button3 setTitle:@"点我3" forState:UIControlStateNormal];
button3.tag = 3;
//设置button的初始状态 已经选择的状态
button3.selected = NO;
//设置自定义按钮两种状态下得不同图片
//未选中状态显示的是第一个图片 选中状态后是后边的一个图片
[button3 setImage:[UIImage imageNamed:@"star_icon@2x.png"] forState:UIControlStateNormal];
[button3 setImage:[UIImage imageNamed:@"star2_Gray@2x.png"] forState:UIControlStateSelected];
[button3 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];
}
//如果有多个按钮要触发同一个操作,但是又想实现不同按钮方法将执行不同操作时,就要判断一下是哪个按钮按下了
- (void)click:(UIButton *)button{
if (button.tag == 2) {
NSLog(@"button2 点我了");
}else if (button.tag == 3){
NSLog(@"button3 点我了");
}
}
2、可以通过设置全局变量来实现
#import "WJJRootViewController.h"
@interface WJJRootViewController (){
<span style="color:#FF0000;">//为全局变量 在此类的任何地方都可以得到此对象
UIButton * _button3;</span>
}
@end
@implementation WJJRootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
3、因为在一个界面中,我们要得到的都是此界面中得控件,所以可以通过下面的方法得到UIButton * btn = (UIButton *)[self.view viewWithTag:3];