Button在执行CAKeyframeAnimation动画时无法响应点击事件。
解决办法:
1、设置动画过程中可以交互。
options:UIViewKeyframeAnimationOptionAllowUserInteraction
[UIView animateKeyframesWithDuration:20 delay:0 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{
self.btn.frame = CGRectMake(100, 300, 100, 100);
} completion:^(BOOL finished) {
NSLog(@"xly--%@",@"finished");
ret = YES;
}];
设置过程中可以交互但是点击button依旧不会响应,因为这时的button已在移动的目标位置,点击目标位置会响应事件。
2、解决移动过程中点击button响应事件
如果点击位置在当前button显示的区域内 return YES
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
if (self.animationAllowUserInteraction) {
CGPoint p = [self convertPoint:point toView:self.superview];
if ([self.layer.presentationLayer hitTest:p]) {
return YES;
}
}
return [super pointInside:point withEvent:event];
}
3、去除动画过程中点击目标位置响应的事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (self.animationAllowUserInteraction) {
CGPoint pS = [touches.anyObject locationInView:self.superview];
if ([self.layer.presentationLayer hitTest:pS]) {
[super touchesBegan:touches withEvent:event];
}
} else {
[super touchesBegan:touches withEvent:event];
}
}
源码:
#import "UIButton+Addtion.h"
#import <objc/runtime.h>
@implementation UIButton (Addtion)
- (void)setAnimationAllowUserInteraction:(BOOL)animationAllowUserInteraction {
objc_setAssociatedObject(self, @selector(animationAllowUserInteraction), @(animationAllowUserInteraction), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)animationAllowUserInteraction {
return objc_getAssociatedObject(self, _cmd);
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
if (self.animationAllowUserInteraction) {
CGPoint p = [self convertPoint:point toView:self.superview];
if ([self.layer.presentationLayer hitTest:p]) {
return YES;
}
}
return [super pointInside:point withEvent:event];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (self.animationAllowUserInteraction) {
CGPoint pS = [touches.anyObject locationInView:self.superview];
if ([self.layer.presentationLayer hitTest:pS]) {
[super touchesBegan:touches withEvent:event];
}
} else {
[super touchesBegan:touches withEvent:event];
}
}
@end
使用:
#import "UIButton+Addtion.h"
//设置button动画过程中响应事件
button.animationAllowUserInteraction = YES;
//设置动画支持响应事件
options:UIViewKeyframeAnimationOptionAllowUserInteraction
demo:
https://github.com/GitHubXuLiying/ButtonAnimationAllowUserInteraction
网友评论