天天看點

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;

}