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

纵饮孤独 提交于 2020-01-04 09:20:15

问题


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...


回答1:


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

    }
}


来源:https://stackoverflow.com/questions/25585543/how-to-change-the-text-color-of-all-text-in-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!