IOS开发基础之时钟的实现

IOS开发基础之时钟的实现

源码在我的主页资源下。
IOS开发基础之时钟的实现_第1张图片

//
//  ViewController.m
//  29-时钟练习
//
//  Created by 鲁军 on 2021/2/21.
//

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,weak)CALayer *second;

@end

@implementation ViewController

- (void)viewDidLoad {
     
    [super viewDidLoad];
    
    
    //self.view.backgroundColor=[UIColor systemPinkColor];
    
    CALayer *clock= [[CALayer alloc] init];
    
    clock.bounds= CGRectMake(0, 0, 200, 200);
    
    
    
    clock.position = CGPointMake(160, 200);
    clock.contents =(__bridge id)([UIImage imageNamed:@"appleWatcher"].CGImage);
    
    
    clock.cornerRadius = 100;
    clock.masksToBounds=YES;
    
    //创建秒针
    CALayer *second = [[CALayer alloc] init];
    second.bounds = CGRectMake(0, 0, 2, 100);
    second.position = clock.position;
    second.backgroundColor = [UIColor redColor].CGColor;
    //锚点 定位点
    second.anchorPoint = CGPointMake(0.5, 0.8);
    
    [self.view.layer addSublayer:clock];
 
        
    [self.view.layer addSublayer:second];
    self.second = second;
    // 定时器
    /*[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
   */
    //显示连接

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeChange)];
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [self timeChange];
}

-(void)timeChange{
     
    CGFloat angle = 2*M_PI/60;
    NSDate *date = [NSDate date];
   /*
    第一种方法
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat =@"ss";
    CGFloat time = [[formatter stringFromDate:date] floatValue];*/
    //第二种方法
    NSCalendar *cal = [NSCalendar currentCalendar];
    CGFloat time2=  [cal component:NSCalendarUnitSecond fromDate:date];
    //self.second.affineTransform = CGAffineTransformRotate(self.second.affineTransform, angle);
    self.second.affineTransform = CGAffineTransformMakeRotation(time2*angle);
}

@end

你可能感兴趣的:(IOS)