Creating an analog clock with hour, minute, and second hands in SwiftUI involves using drawing APIs and a timer to continuously update the clock hands. Here's a basic example of how you could create such a view:
import SwiftUI
struct ContentView: View {
@State private var currentDate = Date()
// A timer that fires every second to update the current date
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
ClockView(currentDate: currentDate)
.onReceive(timer) { input in
currentDate = input
}
}
}
struct ClockView: View {
var currentDate: Date
private var hourHandAngle: Angle {
let hour = Calendar.current.component(.hour, from: currentDate)
let hourAngle = Double(hour % 12) / 12 * 360
return Angle(degrees: hourAngle)
}
private var minuteHandAngle: Angle {
let minutes = Calendar.current.component(.minute, from: currentDate)
let minuteAngle = Double(minutes) / 60 * 360
return Angle(degrees: minuteAngle)
}
private var secondHandAngle: Angle {
let seconds = Calendar.current.component(.second, from: currentDate)
let secondAngle = Double(seconds) / 60 * 360
return Angle(degrees: secondAngle)
}
var body: some View {
ZStack {
Circle() // Clock face
.stroke(lineWidth: 2)
// Hour hand
Rectangle()
.fill(Color.primary)
.frame(width: 3, height: 50)
.offset(y: -25)
.rotationEffect(hourHandAngle)
// Minute hand
Rectangle()
.fill(Color.primary)
.frame(width: 2, height: 70)
.offset(y: -35)
.rotationEffect(minuteHandAngle)
// Second hand
Rectangle()
.fill(Color.red)
.frame(width: 1, height: 90)
.offset(y: -45)
.rotationEffect(secondHandAngle)
Circle() // Center point
.frame(width: 10, height: 10)
}
.frame(width: 200, height: 200)
}
}
@main
struct AnalogClockApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
This code defines a SwiftUI view that displays an analog clock with hours, minutes, and second hands. The ContentView contains a ClockView and uses a Timer to update the current time every second. The ClockView calculates the proper angles for each clock hand based on the current time and displays them accordingly.
The ClockView uses rectangles to represent the clock hands and applies rotation effects to position them correctly. The Circle() at the center represents the pivot point of the clock hands.
Please note that this is a very basic example. For a complete and polished clock, you would need to add tick marks, numerals, and more styling to make it look like a real analog clock. Additionally, you may want to handle time zone changes or daylight saving time adjustments depending on your needs.