2
votes

I have a UIViewControler with 4 layers.

  1. Face Plate of a Watch/Clock
  2. Second Hand
  3. Minute Hand
  4. Hour Hand

I've gotten each hand to start moving onload at the correct time (by defining angles on a circle based on the time the app-loads).

How do I correctly define the motion and duration of motion (should be ad infinitum) using the CABasicAnimation accessor methods?

For instance, I've set my secondHandMotion (which is an instantiated CABasicAnimation object) to being at an angle on the clock frame that corresponds to current time:

CABasicAnimation *secondHandMotion = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
secondHandMotion.fromValue = [NSNumber numberWithFloat:sAlpha];
secondHandMotion.toValue = [NSNumber numberWithFloat:(2*M_PI)];
[secondHand addAnimation:secondHandMotion forKey:@"transform"];

where sAlpha is the angle as a function of time. The secondHandMotion.toValue statement is wrong, I know that. How do I tell it to keep moving, and at the correct interval, 1-second ticks?

Thanks!

2
Alright, so if I add: secondHandMotion.duration = 60.0, I get that it the secondHand makes a full loop in 60 seconds, but then it stops, since I don't know how to have it keep going (forever) after a 2-pi loop.ArtSabintsev

2 Answers

5
votes

When I implemented this in one of my apps I started from this tutorial

Analog Clock using Quartz Core broken link

See Source on Github instead.

It recalculates every second which may give slightly more accurate results relating to the system clock.

The way I implemented the rotation was something like this (this is the animation part you still need the angle calculations you have done previously).

CGAffineTransform transform = CGAffineTransformIdentity;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];

self.hourView.transform   = CGAffineTransformRotate(transform, hourAngle);
self.minView.transform    = CGAffineTransformRotate(transform, minutesAngle);
self.secondView.transform = CGAffineTransformRotate(transform, secondsAngle);

[UIView commitAnimations];

NOTE: I wrote this very early on in my iOS learning so it may be a bit horrible.

1
votes

Have a look at PSAnalogClockView. It nicely solves your problem in a reusable way.