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,552評論 25 708
  • 聲明:原創作品,轉載請注明出處http://www.lxweimin.com/p/c2abd6226897 在上篇文...
    蛇發女妖閱讀 4,721評論 6 56
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,255評論 4 61
  • “好,以后,我保證再也不會給你打電話了。祝你幸福。再見,終于可以如你所愿再也不見了?!蔽易诨疖嚿?,思緒跟隨著你的...
    一只鳥啦閱讀 914評論 18 8
  • 晴好或者下雨的午后,喜歡坐在桌前,翻著閑書,帶白色的耳機,單曲循環一首《蓮的心事》。朋友寄來這本《誰的美又傷了蝶》...
    陶章閱讀 752評論 0 0