buttonアニメーション中にイベントに応答できない解決策

3001 ワード

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 *)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 

@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 *)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