Swift-时钟

时钟的实现主要功能点有时针,分针,秒针旋转的角度,定时刷新,实现效果如下:

时钟.gif

时钟布局:

let bgView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        bgView.center = self.view.center
        self.view.addSubview(bgView)
        
        let clockImgView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        clockImgView.image = UIImage(named: "clock")
        bgView.addSubview(clockImgView)
        
        hourHandView = UIView(frame: CGRect(x: 0, y: 0, width: 3, height: 60))
        hourHandView?.backgroundColor = UIColor.black
        hourHandView?.center = CGPoint(x: 75, y: 75)
        hourHandView?.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
        bgView.addSubview(hourHandView!)
        
        minuteHandView = UIView(frame: CGRect(x: 0, y: 0, width: 2, height: 60))
        minuteHandView?.backgroundColor = UIColor.black
        minuteHandView?.center = CGPoint(x: 75, y: 75)
        minuteHandView?.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
        bgView.addSubview(minuteHandView!)
        
        secondHandView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 60))
        secondHandView?.backgroundColor = UIColor.red
        secondHandView?.center = CGPoint(x: 75, y: 75)
        secondHandView?.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
        bgView.addSubview(secondHandView!)
        
        let displayLink:CADisplayLink = CADisplayLink(target: self, selector: #selector(self.runClock))
        displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)

定时刷新:

 var calendar:Calendar = NSCalendar.current
        calendar.timeZone = NSTimeZone.local
        
        let date:Date = Date()
        
        let second:Int = calendar.component(Calendar.Component.second, from: date)
        let secondAngle:Double = (Double.pi * 2 / 60) * Double(second)
        secondHandView?.transform = CGAffineTransform(rotationAngle: CGFloat(secondAngle))
        
        let minute:Int = calendar.component(Calendar.Component.minute, from: date)
        let minuteAngle:Double = (Double.pi * 2 / 60) * Double(minute)
        minuteHandView?.transform = CGAffineTransform(rotationAngle: CGFloat(minuteAngle))
        
        let hour:Int = calendar.component(Calendar.Component.hour, from: date)
        let hourAngle:Double = (Double.pi * 2 / 12) * Double(hour)
        hourHandView?.transform = CGAffineTransform(rotationAngle: CGFloat(hourAngle))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,142评论 25 708
  • 声明:原创作品,转载请注明出处http://www.jianshu.com/p/c2abd6226897 在上篇文...
    蛇发女妖阅读 4,709评论 6 56
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,223评论 4 61
  • “好,以后,我保证再也不会给你打电话了。祝你幸福。再见,终于可以如你所愿再也不见了。”我坐在火车上,思绪跟随着你的...
    一只鸟啦阅读 903评论 18 8
  • 晴好或者下雨的午后,喜欢坐在桌前,翻着闲书,带白色的耳机,单曲循环一首《莲的心事》。朋友寄来这本《谁的美又伤了蝶》...
    陶章阅读 704评论 0 0