此文学习来源为:http://study.163.com/course/introduction/1002858003.htm
此工程文件实现功能:
1、UIButton的事件的概念
2、UIButton的添加方法
3、UIbutton的响应函数
4、多按钮使用同一事件函数
===========================ViewController.m脚本==============================
//创建按钮函数
-(void)createBtn
{
//创建圆角按钮
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 80, 40);
[btn setTitle:@"按钮" forState:UIControlStateNormal];
//向按钮添加事件函数
//P1:“谁”来实现事件函数,实现的对象就是“谁”
//P2:函数对象,当按钮满足P3事件类型时,调用函数
//P3:UIControlEvent:事件处理函数类型
//UIControlEventTouchUpInside:当手指离开屏幕时并且手指位置在按钮范围内触发事件函数
//UIControlEventTouchDown:当我们的手指触碰到屏幕上时
[btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:btn];
UIButton* btn02=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn02.frame = CGRectMake(100, 200, 80, 40);
[btn02 setTitle:@"按钮02" forState:UIControlStateNormal];
//是可以多个按钮使用同一个事件函数来处理不同按钮的事件
[btn02 addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn02];
//设置按钮的标记
btn.tag = 101;
btn02.tag = 102;
}
-(void)pressBtn02
{
NSLog(@"按钮2被触发!");
}
-(void)touchDown
{
NSLog(@"按钮被触碰!");
}
//参数为调用此函数按钮对象本身
-(void)pressBtn:(UIButton*) btn
{
if (btn.tag == 101) {
NSLog(@"btn pressed!");
}
if (btn.tag == 102) {
NSLog(@"btn02 pressed!");
}
}
//-(void)pressBtn
//{
// NSLog(@"按钮被按下!");
//}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self createBtn];
}
学习总结:
- 重点:UIButton的事件函数的概念
- 难点:UIButton的事件函数的实现
源码链接地址:https://pan.baidu.com/s/1yrOLXZZeu9MiOWtMq5-EGA 密码:7t1l