【发布时间】:2013-03-17 10:14:30
【问题描述】:
我知道如何使用 NSDate 来获取时间并将其显示在 UILabel 中。
我需要显示日期 + 小时和分钟。 知道如何在不忙于等待的情况下保持更新吗?
谢谢!
【问题讨论】:
-
[currentDate description] 会给我当前时间,但我不想一直问...
标签: iphone ios objective-c
我知道如何使用 NSDate 来获取时间并将其显示在 UILabel 中。
我需要显示日期 + 小时和分钟。 知道如何在不忙于等待的情况下保持更新吗?
谢谢!
【问题讨论】:
标签: iphone ios objective-c
使用 NSTimer 更新标签上的时间
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}
-(void)updateTime
{
NSDate *date= [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute
formatter1.dateFormat = @"hh:mm a";// use any format
clockLabel.text = [formatter1 stringFromDate:date];
[formatter1 release];
}
【讨论】:
正如您的 cmets 所说,如果您想在分钟更改时更改 label.text
你应该这样做:
1st:获取当前时间:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
并设置label.text = CURRENTHOUR_AND_YOURMINNUTS;
然后在下一分钟刷新标签,像这样:
第一个,你可以在60 - nowSeconds之后查看
[self performSelector:@selector(refreshLabel) withObject:nil afterDelay:(60 - dateComponents.minute)];
- (void)refreshLabel
{
//refresh the label.text on the main thread
dispatch_async(dispatch_get_main_queue(),^{ label.text = CURRENT_HOUR_AND_MINUTES; });
// check every 60s
[self performSelector:@selector(refreshLabel) withObject:nil afterDelay:60];
}
它会每分钟检查一次,所以效果比上面的答案要多。
当refreshLabel被调用时,表示分钟改变了
【讨论】:
performSelector:afterDelay: 并不比定时器更有效,而且这个解决方案是不必要的复杂化。
performSelector:afterDelay:保证在设定的时间发射。您也不需要主队列或NSDateComponents 的位,而且完全不清楚CURRENTHOUR_AND_YOURMINNUTS; 应该是什么。
NSDateComponents 是获取小时和分钟(通过dateComponents.hour 和dateComponents.minute ),因为他想显示小时和分钟,我不知道他想要什么格式所以我使用CURRENTHOUR_AND_YOURMINNUTS 。并且刷新 UI(label.text) 不能使用主线程?
您可以使用 NSTimer 定期获取当前时间。
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
- (void)timerFired:(NSTimer*)theTimer{
//you can update the UILabel here.
}
【讨论】:
您可以使用 NSTimer ,但是,鉴于上述方法,UILabel 不会在触摸事件上更新,因为主线程将忙于跟踪它。您需要将其添加到 mainRunLOOP
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabelWithDate) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
-(void)updateLabelWithDate
{
//Update your Label
}
您可以更改时间间隔(您希望更新的速率)。
【讨论】:
scheduledTimer... 创建计时器时,它已经添加到运行循环中。这是不必要的。