像数字时钟一样显示时间

时间:2012-06-13 15:59:07

标签: objective-c xcode ipad nsdate nsdateformatter

我可以使用代码

在我的iPad应用程序上显示当前时间
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];


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

但是这只会在加载应用程序时给出时间。我如何有时间继续跑步?就像一个数字时钟。

3 个答案:

答案 0 :(得分:9)

使用此:

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;
}

答案 1 :(得分:6)

实施NSTimer

How do I use NSTimer?

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

然后实现targetMethod来检查并更新你的时间!!!

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

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

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

答案 2 :(得分:0)

注意: - 在.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);

}