本文将介绍一个拥有圆环形状的倒计时器,涉及到的主要内容有路径绘制、动画、多线程和一些时间单位的相互转换,虽然这么多的内容看起来会很复杂,但跟着小编一步一步来实现,你就会发现原来可以这么简单。所以这里不再对这个控件作过多的陈述了,如果这样做的话是会在开头就出现一段不小的篇幅,我想这样你们是不会耐心看下去的(好吧,我承认是我太懒,没想到小学就学会的造句在今天看来是如此的艰难),不瞎扯了,直接上图吧。
----------------------------------------------------------------------------------------还是分割线------------------------------------------------------------------------------
完成效果图
----------------------------------------------------------------------------------------还是分割线------------------------------------------------------------------------------
1. 创建我们的GYCCircularTimer类
- 在Xcode里新建一个类,取名GYCCircularTimer,继承UIView
- 打开GYCCircularTimer.h文件,先从添加属性成员开始,想想一个倒计时器有哪些属性?看图!得有个用于显示它名字的Label吧、还得有个显示剩余时间的Label,圆环这样形状的用半径就可以表示出它的大小了吧、前面的环形圈和后面的环形圈,想想都头大......上代码吧:
@property (assign, nonatomic) CGFloat radius;
@property (strong, nonatomic) CAShapeLayer *foregroundLayer;
@property (assign, nonatomic) CGFloat foregroundPathWidth;
@property (strong, nonatomic) UIColor *foregroundPathColor;
@property (strong, nonatomic) CAShapeLayer *backgroundLayer;
@property (assign, nonatomic) CGFloat backgroundPathWidth;
@property (strong, nonatomic) UIColor *backgroundPathColor;
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *timeLabel;
@property (assign, nonatomic) id <CircularTimerDelegate> delegata;
我没说让读者就照这样写,怎么声明一个类的属性成员我想还是挺有讲究的吧,所以你大可按你自己的方式来定义类成员,但你够懒的话就直接Copy吧,这里另外定义了一个delegate,后面会用到,这里先添加以下代码到文件顶部位置:
@protocol CircularTimerDelegate <NSObject>
- (void)finishedCountDown;
@end
那么接下来就是公共接口的方法了(说明都写在注释里了,对就是给你看绿色字体来着):
/**
* 初始化CircularTimer
*
* @param center 圆心位置
* @param r 半径
* @param width 线宽
* @param color 颜色
* @param isClockWise 是否顺时针
* @param t 标题
* @param h 小时
* @param m 分钟
* @param s 秒
*
* @return CircularTimer实例
*/
- (instancetype)initWithCenter:(CGPoint)center
Radius:(CGFloat)r
PathWidth:(CGFloat )width
PathColor:(UIColor *)color
Clockwis