像数字时钟一样显示时间



我能够使用代码在我的iPad应用程序上显示当前时间,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];

NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
timeLabel.text = currentTime;

但这仅在加载应用程序时提供时间。我如何获得继续跑步的时间?就像一个数字时钟。

使用这个:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES]

选择器方法如下所示:

-(void)targetMethod:(id)sender
{
  NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
  timeLabel.text = currentTime;
}

实现 NSTimer

如何使用 NSTimer?

[NSTimer scheduledTimerWithTimeInterval:1.0     
                                 target:self
                               selector:@selector(targetMethod:)     
                               userInfo:nil     
                                repeats:YES];

然后实现目标方法来检查和更新您的时间!!

如果是我,

我可能会得到初始时间,并且只使用 1 秒计时器更新我的内部时间。

您可以通过实现更快的计时器(假设快 4 到 8 倍)来实现更高的时序分辨率,这样您可能不会经常不同步,但如果这样做,那么您将能够重新同步到 [NSData 日期] 返回的时间。 换句话说,后台任务运行得越快,就越容易与返回的真实时间重新同步。 这也意味着您只需在目标方法中每隔几次检查一次同步。

猜我说的是记住奈奎斯特。 奈奎斯特的理论(本质上)指出,你应该至少以两倍的速度进行采样,而不是你最终尝试使用从抽样中获得的数据集重现的分辨率。 在这种情况下,如果您尝试向用户显示每秒一次的更新,那么您确实应该以不低于 1/2 秒的速度采样,以尝试捕获从一个秒状态到下一个秒状态的转换。

注意 :- 在 .h 文件中声明

@property(nonatomic , weak) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIImageView *imgViewClock; //Image of Wall Clock
@property (weak, nonatomic) IBOutlet UIImageView *hourHandImgView; //Image of Hour hand
@property (weak, nonatomic) IBOutlet UIImageView *minuteHandImgView; //Image of Minute hand
@property (weak, nonatomic) IBOutlet UIImageView *secondHandImgView; //Image of Second hand

注意 :- 在 .m 文件中声明

- (void)viewDidLoad {
[super viewDidLoad];
//Clock
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tick) userInfo:nil repeats:YES];
[self tick];
}
/

/这里分配(勾号)方法

-(void)tick {
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger units = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *Components = [calendar components:units fromDate:[NSDate date]];
CGFloat hours = (Components.hour / 12.0) * M_PI * 2.0;
CGFloat mins = (Components.minute / 60.0) * M_PI * 2.0;
CGFloat seconds = (Components.second / 60.0) * M_PI * 2.0;
self.hourHandImgView.transform = CGAffineTransformMakeRotation(hours);
self.minuteHandImgView.transform = CGAffineTransformMakeRotation(mins);
self.secondHandImgView.transform = CGAffineTransformMakeRotation(seconds);
}

最新更新