更改textLabel以在特定时间更改

时间:2010-11-10 07:11:57

标签: iphone xcode

我试图让textLabel每隔24小时更改一次,有人帮我设置这段代码吗?

这是我正在使用的当前代码。

h fil

NSTimer *timer;

IBOutlet UILabel *textLabel;

m file

(void)onTimer {
static int i = 0;

if ( i == 0 ) { textLabel.text = @"iphone app"; }

else if ( i == 1 ) { textLabel.text = @" Great App!"; }

else if ( i == 2 ) { textLabel.text = @" WOW!"; }

else { textLabel.text = @" great application again!!"; i = -1; }

i++; }

timer =[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

1 个答案:

答案 0 :(得分:0)

尝试使用此代码:

NSDate *date = [NSDate date]; //current date

NSTimeInterval secondsInDay = 24 * 60 * 60;

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
if([components hour] >= 12) {
    //set next day - by adding 24 hours to current day
    NSDate *nextDay = [NSDate dateWithTimeInterval:secondsInDay sinceDate:date];
    //recalculate components
    components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:nextDay];
} 

NSDateComponents *newDateComponents = [[NSDateComponents alloc] init];
[newDateComponents setYear:[components year]];
[newDateComponents setMonth:[components month]];
[newDateComponents setDay:[components day]];
[newDateComponents setHour:12];
[newDateComponents setMinute:0];
[newDateComponents setSecond:0];

NSDate *firingDate = [calendar dateFromComponents:newDateComponents];
[newDateComponents release];

NSTimer *timer = [[NSTimer alloc] initWithFireDate:firingDate interval:secondsInDay target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];

然后实现onTimer方法:

- (void) onTimer:(NSTimer)timer {
   self.textLabel.text = @"Greetings from Poland"; //;)
}