Search code examples
iosuiviewuicolor

How to set text color for all subviews?


For example, I create a UIView which has some UILabel and UIButton subviews inside. All of the subviews has different text colors.

Is there an easy way to set text color for all subviews and cancel it? It should works like mask?


Solution

  • For UIButton, if they are the default type (.RoundedRectType), it's as simple as setting the tintColor property to the one you want on their superview. For UILabel unfortunately that's not enough, but you might subclass UILabel and override the -tintColorDidChange method like so:

    // In MyLabelSubclass.m
    - (void)tintColorDidChange {
        self.textColor = self.tintColor;
    }
    
    // Swift version
    override func tintColorDidChange {
        textColor = tintColor
    }
    

    For more information about why UILabel doesn't automatically update it's textColor when the tintColor changes, this answer is a great explanation of what's going on and the reasoning behind this technical choice.