请帮忙。我想用iphone sdk创建倒数计时器。我有现在的时间:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
和来自数据库的时间。例如:currentTime是19:18:30,数据库的时间是19:20:01。因此,计时器应设置为0:01:31并开始倒计时。当到达0:00:00时,从数据库中取出另一个时间(例如:19:21:00),再次设置计时器(0:00:59)和星号倒计时。当到达0:00:00时,取......计时器应由UILabel显示。
请帮忙。它开始让我发疯。 :)
答案 0 :(得分:8)
试试这个。我刚刚只编写了解决方案所需的方法。不要忘记实现dealloc等。
CountdownViewController.h
@interface CountdownViewController : UIViewController {
IBOutlet UILabel *clockLabel;
NSDate *databaseDate;
NSTimer *timer;
}
@property(nonatomic, retain) IBOutlet UILabel *clockLabel;
@property(nonatomic, retain) NSDate *databaseDate;
@end
CountdownViewController.m
@implementation CountdownViewController
@synthesize clockLabel;
@synthesize databaseDate;
- (void) showClock {
NSTimeInterval remainingSec = [databaseDate timeIntervalSinceNow];
if (!timer || remainingSec <= 0) {
[timer invalidate];
timer = nil;
// getting time from database
self.databaseDate = [NSDate dateWithTimeIntervalSinceNow:20.0];
remainingSec = [databaseDate timeIntervalSinceNow];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(showClock)
userInfo:nil
repeats:YES];
}
NSInteger hours = remainingSec / 3600;
NSInteger remainder = ((NSInteger)remainingSec)% 3600;
NSInteger minutes = remainder / 60;
NSInteger seconds = remainder % 60;
clockLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
@end