天天看点

iOS 数字时钟(时间显示并持续更新)

思路分析:

要实现数字时钟,需要想到两个方面:当前时间、持续更新。这两方面其实都不难,但是还是记录下来,(runloop和NSDate结合)获取当前时间用NSDate,持续跟新是把获取时间的方法写进runloop。这样结合一下就可以不短显示最新的时间了。

代码示例:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //定时器 反复执行
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    
//设置停止按钮
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 100, 40)];
    
    [button setTitle:@"STOP" forState:UIControlStateNormal];
    
    }


-(void)updateTime{
    UILabel *timeLable = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 300, 60)];
    
    timeLable.backgroundColor = [UIColor orangeColor];
    
    [self.view addSubview:timeLable];
    
    
    NSDate *currentDate = [NSDate date];
    
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc]init];
    
    [dataFormatter setDateFormat:@"YYYY - MM - dd   HH : mm : ss "];
    
    NSString *dateString = [dataFormatter stringFromDate:currentDate];
    NSLog(@"%@",dateString);
    
    timeLable.text = dateString;

}