Home > Software design >  Current time is not displayed in the analog view
Current time is not displayed in the analog view

Time:11-12

I have just recently started using Swiftui and have the following question: I would like to convert the current time to an analog view. But when I use the code below, I always get an error message at the angle. What is the reason that it does not work?

enter image description here

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 {
        Hand(inset: 50, angle: currentDate.hourAngle)
            .stroke(lineWidth: 4)
            .foregroundColor(.black)
        Hand(inset: 22, angle: currentDate.minuteAngle)
            .stroke(lineWidth: 4)
            .foregroundColor(.black)
        Hand(inset: 10, angle: currentDate.secondAngle)
            .stroke(lineWidth: 2)
            .foregroundColor(.gray)
    }
    .onReceive(timer) { (input) in
        self.currentDate = input
    }}}

CodePudding user response:

Based on the link you provided, It looks like the author of the article did not provide some extensions. Add the following extensions to your code (preferable in a new file), and you should be good

  • Related