Return to Snippet

Revision: 66408
at May 1, 2014 00:07 by sidneydekoning


Initial Code
@property (weak, nonatomic) IBOutlet UIImageView *hourHands;
@property (weak, nonatomic) IBOutlet UIImageView *minuteHands;
@property (weak, nonatomic) IBOutlet UIImageView *secondHands;
@property (weak, nonatomic) NSTimer *timer;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.secondHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
    self.minuteHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
    self.hourHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateClockHands) userInfo:nil repeats:YES];
    
    // Make sure user does not see uncalibrated hands at 0,0 position.
    [self updateClockHands];
}

-(void) updateClockHands
{
    NSCalendar *cal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    NSDateComponents *components = [cal components:units fromDate:[NSDate date]];
    
    CGFloat hoursAngle = (components.hour /12.0) * M_PI * 2.0;
    CGFloat minsAngle = (components.minute / 60.0) * M_PI * 2.0;
    CGFloat secsAngle = (components.second / 60.0) * M_PI * 2.0;

    // Now you can adjust the hands of a clock 
    // Assuming hourHands, minuteHands, secondHands are UIImageview's and are setup as properties in .m
    self.hourHands.transform = CGAffineTransformMakeRotation(hoursAngle);
    self.minuteHands.transform = CGAffineTransformMakeRotation(minsAngle);
    self.secondHands.transform = CGAffineTransformMakeRotation(secsAngle);
}

Initial URL


Initial Description
Simple calculation for a clock

Initial Title
Calculating angle of clock hands

Initial Tags


Initial Language
Objective C