Skip to content

Instantly share code, notes, and snippets.

@cedricbahirwe
Last active May 3, 2023 17:22
Show Gist options
  • Save cedricbahirwe/53b35c647195538ce4c133d173bec9ae to your computer and use it in GitHub Desktop.
Save cedricbahirwe/53b35c647195538ce4c133d173bec9ae to your computer and use it in GitHub Desktop.
// Answer to https://stackoverflow.com/questions/69929331/current-time-is-not-displayed-in-the-analog-view
struct Hand: Shape {
let inset: CGFloat
let angle: Angle
func path(in rect: CGRect) -> Path {
let rect = rect.insetBy(dx: inset, dy: inset)
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.midY))
path.addRoundedRect(in: CGRect(x: rect.midX - 4, y: rect.midY - 4, width: 8, height: 8), cornerSize: CGSize(width: 8, height: 8))
path.move(to: CGPoint(x: rect.midX, y: rect.midY))
path.addLine(to: position(for: CGFloat(angle.radians), in: rect))
return path
}
private func position(for angle: CGFloat, in rect: CGRect) -> CGPoint {
let angle = angle - (.pi/2)
let radius = min(rect.width, rect.height)/2
let xPosition = rect.midX + (radius * cos(angle))
let yPosition = rect.midY + (radius * sin(angle))
return CGPoint(x: xPosition, y: yPosition)
}
}
struct TickHands: View {
@State private var currentDate = Date()
let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
var body: some View {
ZStack {
Group {
Hand(inset: 50, angle: currentDate.hourAngle)
.stroke(style: StrokeStyle(lineWidth: 4.0, lineCap: .round))
Hand(inset: 22, angle: currentDate.minuteAngle)
.stroke(style: StrokeStyle(lineWidth: 4.0, lineCap: .round))
}
.foregroundColor(.black)
Hand(inset: 10, angle: currentDate.secondAngle)
.stroke(style: StrokeStyle(lineWidth: 2, lineCap: .round))
.foregroundColor(.gray)
}
.onReceive(timer) { (input) in
self.currentDate = input
}
}
}
extension Date {
var hourAngle: Angle {
return Angle (degrees: (360 / 12) * (self.hour + self.minutes / 60))
}
var minuteAngle: Angle {
return Angle(degrees: (self.minutes * 360 / 60))
}
var secondAngle: Angle {
return Angle (degrees: (self.seconds * 360 / 60))
}
}
extension Date {
var hour: Double {
return Double(Calendar.current.component(.hour, from: self))
}
var minutes: Double {
return Double(Calendar.current.component(.minute, from: self))
}
var seconds: Double {
return Double(Calendar.current.component(.second, from: self))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment