2012-10-29 81 views
0

我有一段代碼可以在一天中的每個小時以不同的方式生成梯度視圖。如果關閉,當然每個小時開放的應用程序每小時刷新一次視圖

- (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; 
} 

㈡工作正常,但它可以被執行,這樣它會自動更改每隔一小時,而應用程序正在運行?我可以以某種方式實現一個函數來檢查它是否是整整一個小時,並重新創建視圖?

回答

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 
} 
+0

所以它的安全遍地調用整個方法?我認爲視圖應該被破壞,然後創建:D – 1337code

+1

此代碼不會在應用程序的開始處生成視圖,並且我希望它會在每個整小時內更改,例如下午1點,下午2點,下午3點... – 1337code