iOS开发值得学习iOS博客好东西

播放按钮|动画|runtime

2017-08-06  本文已影响236人  艾江山

前言

APP做得好不在于一些细节的处理,用户可以看得到,但是也最容易忽略,我们要提升体验,但是用户又感觉不到。这篇文章主要处理播放按钮的动画,以及runtime中Method Swizzling 使用;
我们先来看看效果:


效果

效果很细微,不容易被用户察觉,所以长期看也不会觉得厌烦。

实现

初始化

按钮很简单,我们直接用CAShapeLayer画出来,因为CAShapeLayer有强大的path属性所以我选着它
按钮在暂停的时候有三条线段,播放的时候两条线段。我直接初始化三条线段;

线段

动画

动画还是直接调用path属性

/**
 path动画

 @param path 变为的path
 @param duration 持续时间
 @return 返回动画
 */
- (CABasicAnimation*)animationToPath:(UIBezierPath* )path duration:(NSTimeInterval)duration {
    CABasicAnimation    *pathAnimation   = [CABasicAnimation animationWithKeyPath:@"path"];
    pathAnimation.toValue                = (__bridge id)(path.CGPath);
    pathAnimation.fillMode               = kCAFillModeForwards;
    pathAnimation.removedOnCompletion    = NO;
    pathAnimation.duration               = duration;
    return pathAnimation;
}

layer3的时候会有出现和消失,这里会做一个不透明度的动画

/**
 不透明度动画
 
 @param layer 要执行动画的layer
 @param from 从多少开始
 @param to 到多少
 */
- (void)opacityAnimationWithLayer:(CALayer*)layer fromValue:(CGFloat)from toValue:(CGFloat)to {
    CABasicAnimation *opacityAnimation           = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.toValue                     = @(to);
    opacityAnimation.fromValue                   = @(from);
    opacityAnimation.duration                    = .2;
    opacityAnimation.fillMode                    = kCAFillModeForwards;
    opacityAnimation.removedOnCompletion         = NO;
    [layer addAnimation:opacityAnimation forKey:nil];
}

动画很简单接下来是替换系统方法

+(void)load {

    SEL actionA   = @selector(sendAction:to:forEvent:);
    SEL actionB   = @selector(__ai__sendAction:to:forEvent:);
    //原有的方法
    Method aMetod =   class_getInstanceMethod([AIPlayerButton class],actionA);
    //自定义的方法
    Method bMetod = class_getInstanceMethod([AIPlayerButton class], actionB);
    //这句是为了保护系统的方法
    BOOL isAdd = class_addMethod([AIPlayerButton class], actionA, method_getImplementation(bMetod), method_getTypeEncoding(bMetod));
    if (isAdd) {
        class_replaceMethod([AIPlayerButton class], actionB, method_getImplementation(aMetod), method_getTypeEncoding(aMetod));
    }else{
        method_exchangeImplementations(aMetod, bMetod);
    }
}
- (void)__ai__sendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event {
    if (self.ignoreEvent) {
        return;
    }
    if (self.acceptEventInterval > 0) {
        self.ignoreEvent  = YES;
        [self performSelector:@selector(setIgnoreEvent:) withObject:@(NO) afterDelay:self.acceptEventInterval];
        if (self.isSelected) {
            [self changeToPlayingAnimation];
        } else {
            [self changeToStopAnimation];
        }
        [self __ai__sendAction:action to:target forEvent:event];
    }
}

对于可以看OC Method Swizzling 使用
源码已放在GitHub上喜欢的给个star支持下
源码位置

源码位置
参考博客:http://www.cocoachina.com/ios/20150911/13260.html
上一篇 下一篇

猜你喜欢

热点阅读