完成了 AngleUtility 後,在 ClockContainerView init 完,就可以使用了。
private let angleUtility: AngleUtility = .init()
/// 還沒做 AngleUtility 之前
private func updateTime() {
let timestamp = Date().timeIntervalSince1970
print("current timestamp: \(timestamp)")
}
/// 做出 AngleUtility 後
private func updateTime() {
let timestamp = Date().timeIntervalSince1970
secondDegree = angleUtility.getBackwardsSecondHandRadius(from: timestamp)
minuteDegree = angleUtility.getBackwardsMinuteHandRadius(from: timestamp)
hourDegree = angleUtility.getBackwardsHourHandRadius(from: timestamp)
}
整個 App run 起來後,你就可以看到時鐘是逆著走的,這不是鏡像鐘喔,在程式邏輯上,是逆著走。當時的葛麗絲,應該是用機械裝置組合出一個逆著走的鐘,用這個 app 來致敬她的想法。
不過,當時的三根針,是用三角形的,所以底部不是很好看。我們在上面貼個圓型,來美化他。全部的程式碼如下。
//
// ClockContainerView.swift
// DemoBackwardsClock
//
// Created by cm0679 on 2022/8/31.
//
import SwiftUI
struct ClockContainerView: View {
var width: CGFloat = 200
var height: CGFloat = 200
@State var hourDegree: Double = 0
@State var minuteDegree: Double = 0
@State var secondDegree: Double = 0
private let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
private let angleUtility: AngleUtility = .init()
var body: some View {
ZStack {
ClockDialView()
HandShape(handLength: .hour)
.fill(Color.blue)
.rotationEffect(Angle(degrees: hourDegree))
HandShape(handLength: .minute)
.fill(Color.cyan)
.rotationEffect(Angle(degrees: minuteDegree))
HandShape(handLength: .second)
.fill(Color.red)
.rotationEffect(Angle(degrees: secondDegree))
Circle()
.fill(Color.orange)
.frame(width: 20, height: 20, alignment: .center)
}
.frame(width: width, height: height, alignment: .center)
.onReceive(timer) { _ in
updateTime()
}
}
private func updateTime() {
let timestamp = Date().timeIntervalSince1970
secondDegree = angleUtility.getBackwardsSecondHandRadius(from: timestamp)
minuteDegree = angleUtility.getBackwardsMinuteHandRadius(from: timestamp)
hourDegree = angleUtility.getBackwardsHourHandRadius(from: timestamp)
}
}
struct ClockContainerView_Previews: PreviewProvider {
static var previews: some View {
ClockContainerView()
}
}
最後完成的樣子,上傳個一分鐘影片到 Youtube