所有的UI控件都继承了UIView,UIView则是继承了UIResponder(用户操作响应者)。
UI大致可以分为三类:
一.活动控件:大部分继承UIControl,如UIButton;
二.静态控件:只继承UIView,并不继承UIControl,如UILabel、UIImageView;
三.被动控件:接受用户操作,但不激发事件;
在UIControl中,有三个比较常用的与用户交互的方法
//用户开始触碰时激发
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//用户连续触碰时激发
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//用户结束触碰时激发
- (void)endTrackingWithTouch:(nullable UITouch *)touch withEvent:(nullable UIEvent *)
所以,我们可以通过重写这三个方法,实现某些特定的效果,比如某个Button的心跳效果,即当用户点击时放大,结束点击再缩小。上代码:
自定义一个UIButton,重写begin和end方法
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
CGRect rect = self.frame;
CGPoint center = self.center;
rect.size.width += 5;
rect.size.height += 5;
self.layer.cornerRadius = rect.size.width / 2;
self.frame = rect;
self.center = center;
return YES;
}
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
CGRect rect = self.frame;
CGPoint center = self.center;
rect.size.width -= 5;
rect.size.height -= 5;
self.layer.cornerRadius = rect.size.width / 2;
self.frame = rect;
self.center = center;
}
在controller中去创建自己的Button,并添加点击事件
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self createTestButton];
}
- (void)createTestButton
{
float bw = 50;
float bh = 50;
mb = [YHButton buttonWithType:UIButtonTypeSystem];
//设置frame值
mb.frame = CGRectMake((screen_width - bw) / 2, (screen_height - bh) / 2, bw, bh);
mb.backgroundColor = [UIColor orangeColor];
mb.tag = 201;
[mb addTarget:self action:@selector(testButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
mb.highlighted = NO;
mb.layer.cornerRadius = bw / 2;
[self.view addSubview:mb];
}
- (void)testButtonClicked:(UIButton *)sender
{
NSLog(@"被点了");
}
这样,一个Button就实现了点击之后的心跳效果。