0

I have a code which generates gradient view differently for every hour in a day.

- (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 works fine if you close an open an app every hour of course, but can it be implemented so that it automatically changes every hour while the app is running? Can I somehow implement a function that will check if it is the full hour, and recreate the view?

4

1 回答 1

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
}
于 2012-10-29T07:56:29.733 回答