iOS 按钮如何边动画边实现点击事件

常规思路,移动frame,这种方法是行不通的,在按钮移动的时候,只能点击按钮的最终位置才会响应事件,点击按钮本身是无效的.代码如下

- (void)viewDidLoad {
    [super viewDidLoad];
    [self uiConfig];
}
- (void)uiConfig
{
    _btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    _btn.backgroundColor = [UIColor purpleColor];
    [_btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
    
    [UIView animateWithDuration:10.f delay:2.f options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear animations:^{
        _btn.frame = CGRectMake(0, 400, 100, 100);
    } completion:^(BOOL finished) {
        
    }];

}
- (void)btnClick
{
_btn.backgroundColor = [UIColor colorWithRed:(arc4random()%255)/ 255.f green:(arc4random()%255)/ 255.f blue:(arc4random()%255)/ 255.f alpha:1];
}



既然frame行不通,我们改用layer层,因为btn的视觉呈现是通过layer层,这里会用到一个很重要的属性,presentationLayer.

- (void)uiConfig
{
    _btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    _btn.backgroundColor = [UIColor purpleColor];
    [_btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
    
    [UIView animateWithDuration:10.f delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear animations:^{
        _btn.layer.transform = CATransform3DMakeTranslation(0, 400, 0);
    } completion:^(BOOL finished) {
        
    }];

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{
    
    UITouch *touch = touches.anyObject;
    CGPoint touchPoint = [touch locationInView:self.view];
    
    if (CGRectContainsPoint(((CALayer *)[_btn.layer presentationLayer]).frame, touchPoint))
   {
        [self btnClick];
    }
}
- (void)btnClick
{
_btn.backgroundColor = [UIColor colorWithRed:(arc4random()%255)/ 255.f green:(arc4random()%255)/ 255.f blue:(arc4random()%255)/ 255.f alpha:1];
}

Untitled.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容