button执行frame动画响应点击事件

在实现frame动画过程中,遇到点击事件响应问题,即按钮在动画未完成时点击目标位置也会响应。通过比较点击位置与动画当前坐标解决了这一问题,确保移动中的button能正确识别点击事件。
摘要由CSDN通过智能技术生成

如果按照常规方法去写这个过程,代码如下:

@interface ViewController ()
@property (nonatomic, strong) UIButton * button;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
  self.button.backgroundColor = [UIColor redColor];
  [self.button addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:self.button];

  //设置动画匀速并且在运动期间打开用户交互
  [UIView animateWithDuration:10.f 
  delay:0 
  options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction 
  animations:^{
     self.button.frame = CGRectMake(0, 400, 100, 100);
  } completion:^(BOOL finished) { 
  }];
}

- (void)btnClicked{
    NSLog(@"button clicked");
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

会发现在动画还没有运行到目标位置的时候,直接点击目标位置也会响应点击事件。
这里写图片描述

更改代码如下:通过对比点击位置与动画当前坐标的方法来准确响应点击事件

@interface ViewController ()
@property (nonatomic, strong) UIButton * button;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    self.button.backgroundColor = [UIColor redColor];
//    关闭按钮的用户交互,使得点击事件穿透按钮,到达self.view
    self.button.userInteractionEnabled = NO;
    [self.view addSubview:self.button];

    //设置动画匀速并且在运动期间打开用户交互
    [UIView animateWithDuration:10.f delay:0 options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction animations:^{
        self.button.frame = CGRectMake(0, 400, 100, 100);
    } completion:^(BOOL finished) {

    }];
}

//点击事件
- (void)btnClicked{
    NSLog(@"button clicked");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //获取点击点坐标
    CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
    //获取动画当前中心点坐标
    CGPoint currentPosition = [[self.button.layer presentationLayer] position];
    if (touchPoint.x > currentPosition.x - 50 && touchPoint.x < currentPosition.x + 50 && touchPoint.y > currentPosition.y - 50 && touchPoint.y < currentPosition.y + 50) {
        [self btnClicked];
    }
}

更改后,移动中的button就可以正常识别点击事件了
这里写图片描述

本文借鉴http://www.cnblogs.com/YouXianMing/p/4149103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值