Christian Seiler
Christian Seiler

Reputation: 1140

How to change the text color of all text in UIView?

I'm building an iOS app that features 2 themes (dark and light) where the background changes colours.

My problem now is the change of the text colour. How can I set the text colour of all labels to lightTextColor?

This is where I change the colours:

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

The text colour change has to get in there somehow...

Upvotes: 2

Views: 4566

Answers (1)

Sebyddd
Sebyddd

Reputation: 4315

Loop through all the UIView's in self.view.subviews and check if it's of type UILabel. If it is, cast the view to a label and set the color.

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

    }
}

Upvotes: 6

Related Questions