iOS系列UI篇——UIControl

所有的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就实现了点击之后的心跳效果。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值