swift Swift Playgrounds模拟时钟示例。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift Playgrounds模拟时钟示例。相关的知识,希望对你有一定的参考价值。
import SpriteKit
import PlaygroundSupport
class Scene: SKScene {
var hands: [String: SKShapeNode] = [:]
override func didMove(to view: SKView) {
let center = CGPoint(x: frame.midX, y: frame.midY)
let radius = CGFloat(450)
let face = SKShapeNode(circleOfRadius: radius)
face.position = center
face.lineWidth = 10
face.strokeColor = #colorLiteral(red: 0.8039215803146362, green: 0.8039215803146362, blue: 0.8039215803146362, alpha: 1.0)
face.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
addChild(face)
for i in 1 ... 12 {
let label = SKLabelNode()
label.text = String(i)
label.fontSize = 100
label.fontColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
let a = 2 * CGFloat.pi * CGFloat(i) / CGFloat(12)
let b = CGFloat(380)
let c = label.frame.height / 2
let x = sin(a) * b
let y = cos(a) * b - c
label.position = CGPoint(x: x, y: y)
face.addChild(label)
}
let attrs: [(String, CGFloat, CGFloat, UIColor)] = [
("m", 350, 8, #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)),
("h", 280, 12, #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)),
("s", 350, 4, #colorLiteral(red: 0.8078431487083435, green: 0.027450980618596077, blue: 0.3333333432674408, alpha: 1.0))
]
for (name, length, width, color) in attrs {
let p = CGMutablePath()
p.move(to: CGPoint(x: 0, y: length))
p.addLine(to: CGPoint(x: 0, y: 0))
let s = SKShapeNode(path: p)
s.lineWidth = width
s.strokeColor = color
s.lineCap = .round
hands[name] = s
face.addChild(s)
}
}
override func update(_ currentTime: TimeInterval) {
let now = Date()
let cal = Calendar.current
let hh = CGFloat(cal.component(.hour, from: now))
let mm = CGFloat(cal.component(.minute, from: now))
let ss = CGFloat(cal.component(.second, from: now))
let tick = -2 * CGFloat.pi / 60
let s = tick * ss
let m = tick * mm
let tock = -2 * CGFloat.pi / 12
let h = tock * (hh + mm / 60)
hands["s"]?.zRotation = s
hands["m"]?.zRotation = m
hands["h"]?.zRotation = h
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
let r = CGRect(x: 0, y: 0, width: 1000, height: 1000)
let s = Scene(size: r.size)
s.scaleMode = .aspectFit
let v = SKView(frame: r)
v.showsDrawCount = true
v.showsNodeCount = true
v.showsFPS = true
v.presentScene(s)
view = v
}
}
PlaygroundPage.current.liveView = ViewController()
PlaygroundPage.current.wantsFullScreenLiveView = true
以上是关于swift Swift Playgrounds模拟时钟示例。的主要内容,如果未能解决你的问题,请参考以下文章
iPad 上的 Swift Playgrounds 无法按预期使用 SwiftUI 代码
Swift 中 Playgrounds 的用途是啥?
如何在 XCode 8 Playgrounds 中使用 Swift 2.3?
第42月第5天 Swift Playgrounds Mac 版上线
Swift Playgrounds 中的 JavaScriptCore
Swift Playgrounds 是如何工作的?