倒计时按钮效果
by 伍雪颖
@implementationCountButton {
UIColor
*normal_bgColor;
UIColor *enabled_bgColor;
NSTimer *timer;
NSInteger startCount;
NSInteger originNum;
UILabel *timeLabel;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super
initWithFrame:frame];
if (self) {
normal_bgColor = [UIColor
redColor];
enabled_bgColor = [UIColor
lightGrayColor];
startCount =
0;
originNum =
0;
[self
setTitleColor:[UIColor
whiteColor]
forState:UIControlStateNormal];
self.titleLabel.font
= [UIFont
systemFontOfSize:17];
self.backgroundColor
=
normal_bgColor;
startCount =
5;
originNum =
5;
[self
addLabel];
[self
addTarget:self
action:@selector(startCountDown)
forControlEvents:UIControlEventTouchUpInside];
}
return
self;
}
- (void)startCountDown {
timer = [NSTimer
scheduledTimerWithTimeInterval:1
target:self
selector:@selector(countDown)
userInfo:nil
repeats:YES];
self.backgroundColor
=
enabled_bgColor;
self.enabled
=
NO;
[self
numAnimation];
}
- (void)countDown {
startCount--;
timeLabel.text
=
@(startCount).stringValue;
if (startCount
<
0) {
if (timer
==
nil) {
return;
}
[timeLabel.layer
removeAllAnimations];
timeLabel.text
=
@(originNum).stringValue;
[timer
invalidate];
timer =
nil;
self.enabled
=
YES;
startCount =
originNum;
self.backgroundColor
=
normal_bgColor;
}
}
- (void)numAnimation {
CAKeyframeAnimation *scale = [CAKeyframeAnimation
animationWithKeyPath:@"transform.scale"];
scale.keyTimes
=
@[@0,@0.5,@1];
scale.values
=
@[@1,@1.5,@2];
scale.duration
=
1;
CAKeyframeAnimation *opacity = [CAKeyframeAnimation
animationWithKeyPath:@"opacity"];
opacity.keyTimes
=
@[@0,@0.5,@1];
opacity.values
=
@[@1,@0.5,@0];
opacity.duration
=
1;
CAAnimationGroup *animGroup = [CAAnimationGroup
animation];
animGroup.animations
=
@[scale, opacity];
animGroup.duration
=
1;
animGroup.repeatCount
=
HUGE;
animGroup.removedOnCompletion
=
false;
animGroup.beginTime
=
CACurrentMediaTime();
[timeLabel.layer
addAnimation:animGroup
forKey:@"animatjion"];
[self.layer
addSublayer:timeLabel.layer];
}
- (void)addLabel {
timeLabel = [[UILabel
alloc]
init];
timeLabel.frame
=
CGRectMake(0,
0,
CGRectGetWidth(self.frame),
CGRectGetHeight(self.frame));
timeLabel.backgroundColor
= [UIColor
clearColor];
timeLabel.font
= [UIFont
systemFontOfSize:17];
timeLabel.textAlignment
=
NSTextAlignmentCenter;
timeLabel.text
=
@(originNum).stringValue;
[self
addSubview:timeLabel];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。