Swift利用纯代码实现时钟效果实例代码
前言
在刚开始学习iOS开发时,我制作了OneClock,它除了使用最多的翻页时钟效果,还拥有最常见的时钟样式。
今天用一个很简单的方式为大家展示如何实现时钟效果。
1.分别创建时针、分针、秒针
2.随着时间改变进行对应旋转
一、创建时针、分针、秒针
分别创建三个指针的同时,我们初始化了他们的位置,也就是在12点的方向。
这里我只贴出创建的代码,在使用的过程中可以根据需要进行放置。其中hourLength、minuteLength、secondLength分别代表三个指针的长度,在实际使用中根据页面情况进行调整大小。
//创建一个时针VIEW lethourView:UIView!=UIView.init() hourView.center=self.view.center hourView.layer.bounds=CGRect(x:0,y:0,width:2,height:hourLength) hourView.backgroundColor=PolarTheme.bottomColor hourView.layer.anchorPoint=CGPoint(x:1,y:1) hourView.layer.cornerRadius=1 self.hourView=hourView self.view.addSubview(self.hourView) //创建一个分针VIEW letminuteView:UIView!=UIView.init() minuteView.center=self.view.center minuteView.layer.bounds=CGRect(x:0,y:0,width:Int(1.5),height:Int(minuteLength)) minuteView.backgroundColor=PolarTheme.bottomColor minuteView.layer.anchorPoint=CGPoint(x:1,y:1) self.minuteView=minuteView self.view.addSubview(self.minuteView) //创建一个秒针VIEW letsecondView:UIView!=UIView.init() secondView.center=self.view.center secondView.layer.bounds=CGRect(x:0,y:0,width:1,height:secondLength) secondView.backgroundColor=PolarTheme.topColor secondView.layer.anchorPoint=CGPoint(x:1,y:1) self.secondView=secondView self.view.addSubview(self.secondView)
二、时间跟踪器
创建指针只是时钟的第一步,之后我们需要用时间来改变对应的指针位置。所以在创建指针之后,我们需要紧跟着一个时间监视器,通过move函数来调整指针方向。
先定义Timer
vartimer:Timer!
再为Timer绑定函数,时间间隔为0.2秒执行一次move
timer=Timer.scheduledTimer(timeInterval:0.2,target:self,selector:#selector(PolarViewController.move),userInfo:nil,repeats:true)
三、改变指针位置
实现原理是,先在函数move()中定义每个指针旋转的大小,再进行周期性刷新位置。
funcmove(){ varangleSecond:CGFloat=CGFloat(Double.pi*2/60.0) varangleMinute:CGFloat=CGFloat(Double.pi*2/60.0) varangleHour:CGFloat=CGFloat(Double.pi*2/12.0) //当前时间 letdate=Date() letcalendar=NSCalendar.current letsecondInt=CGFloat(calendar.component(.second,from:date)) letminuteInt=CGFloat(calendar.component(.minute,from:date)) lethourInt=CGFloat(calendar.component(.hour,from:date)) //计算旋转角度 angleSecond=angleSecond*secondInt angleMinute=angleMinute*minuteInt+angleSecond/60.0 angleHour=angleHour*hourInt+angleMinute/60.0 //保持中心点 self.secondView.center=self.view.center self.minuteView.center=self.view.center self.hourView.center=self.view.center //旋转各自的角度 self.secondView.transform=CGAffineTransform(rotationAngle:angleSecond) self.minuteView.transform=CGAffineTransform(rotationAngle:angleMinute) self.hourView.transform=CGAffineTransform(rotationAngle:angleHour) }
四、手机旋转后的页面刷新
最后增加在旋转模式下的自动刷新,帮助修正显示。
overridefuncwillRotate(totoInterfaceOrientation:UIInterfaceOrientation,duration:TimeInterval){ move() }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。