每小时重新加载视图

时间:2012-10-29 07:43:26

标签: iphone view gradient reload hour

我有一个代码,可以在一天中的每个小时生成不同的渐变视图。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //[self.view setBackgroundColor:[UIColor whiteColor]];

    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc]
                              initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components =
    [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];

    NSInteger hour = [components hour];

    float dayRed;
    float dayGreen;
    float dayBlue;

    float nightRed;
    float nightGreen;
    float nightBlue;

    BOOL from0to12 = NO;
    BOOL from12to24 = NO;

    if (hour >= 0 && hour <= 12) {
        from0to12 = YES;
    }
    else if (hour > 12 && hour <= 23) {
        from12to24 = YES;
    }

    if (from0to12)
    {
        NSLog(@"%d AM", hour);

        dayRed = 0.0;
        dayGreen = 0.0;
        dayBlue = 1 - (0.083333333333 * hour);

        NSLog(@"%f, %f, %f", dayRed, dayGreen, dayBlue);

        nightRed = 0.083333333333 * hour;
        nightGreen = (0.083333333333 * hour)/2;
        nightBlue = 0;

        NSLog(@"%f, %f, %f", nightRed, nightGreen, nightBlue);
    }
    else if (from12to24)
    {
        NSLog(@"%d AM", hour);

        hour = 24-hour;

        dayRed = 0.083333333333 * hour;
        dayGreen = (0.083333333333 * hour)/2;
        dayBlue = 0;

        NSLog(@"%f, %f, %f", dayRed, dayGreen, dayBlue);

        nightRed = 0;
        nightGreen = 0;
        nightBlue = 1-(0.083333333333 * hour);

        NSLog(@"%f, %f, %f", nightRed, nightGreen, nightBlue);
    }


    UIColor *day = [UIColor colorWithRed:dayRed green:dayGreen blue:dayBlue alpha:1.0];

    UIColor *night = [UIColor colorWithRed:nightRed green:nightGreen blue:nightBlue alpha:1.0];

    GradientView *gradient = [[GradientView alloc] initWithFrame:CGRectMake(0,0,320,50)];
    [gradient setColoursWithCGColors:day.CGColor:night.CGColor];

    self.view = gradient;
}

如果你每小时关闭一个应用程序,Ii工作正常,但它是否可以实现,以便在应用程序运行时每小时自动更改?我可以以某种方式实现一个函数来检查它是否是整个小时,并重新创建视图?

1 个答案:

答案 0 :(得分:1)

每1小时安排一次计时器

-(void)viewDidLoad
{
    [NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(loadGradient:) userInfo:nil repeats:YES];
}

-(void)loadGradient:(id)sender
{
    // Do your code for effect every 1 hour
}