如何更改UIView中所有文本的文本颜色?

时间:2014-08-30 18:27:52

标签: ios objective-c xcode textcolor

我正在构建一个iOS应用程序,其中包含2个主题(黑暗和浅色),背景会改变颜色。

我现在的问题是文字颜色的变化。如何将所有标签的文字颜色设置为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];
    }
}

文本颜色变化必须以某种方式进入...

1 个答案:

答案 0 :(得分:6)

循环遍历UIView's中的所有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];
            }
        }

    }
}