2014-08-30 71 views
2

我正在構建一個iOS應用程序,其特點是背景改變顏色的2個主題(黑暗與光明)。如何更改UIView中所有文本的文本顏色?

我現在的問題是文字顏色的變化。如何將所有標籤的文字顏色設置爲lightTextColor

這是我改變顏色:

- (void)changeColor { 
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults]; 
    NSString *themeSetting = [standardDefaults stringForKey:@"themeKey"]; 
    if ([themeSetting isEqualToString:@"lightTheme"]) { 
     self.view.backgroundColor = [UIColor whiteColor]; 
    } else { 
     self.view.backgroundColor = [UIColor blackColor]; 
    } 
} 

的文本顏色的變化必須通過所有的UIView's在那裏得到的莫名其妙...

回答

6

循環中self.view.subviews並檢查它的類型的UILabel的。如果是,將視圖轉換爲標籤並設置顏色。

- (void)changeColor { 
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults]; 
    NSString *themeSetting = [standardDefaults stringForKey:@"themeKey"]; 
    if ([themeSetting isEqualToString:@"lightTheme"]) { 
     self.view.backgroundColor = [UIColor whiteColor]; 
    } else { 
     self.view.backgroundColor = [UIColor blackColor]; 

     //Get all UIViews in self.view.subViews 
     for (UIView *view in [self.view subviews]) { 
      //Check if the view is of UILabel class 
      if ([view isKindOfClass:[UILabel class]]) { 
       //Cast the view to a UILabel 
       UILabel *label = (UILabel *)view; 
       //Set the color to label 
       label.textColor = [UIColor redColor]; 
      } 
     } 

    } 
} 
+0

謝謝。這工作 – 2014-08-30 18:52:47