1

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?

xi.lin
  • 3,326
  • 2
  • 31
  • 57

4 Answers4

4

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.

Community
  • 1
  • 1
Gianluca Tranchedone
  • 3,598
  • 1
  • 18
  • 33
1

You can run a loop on subviews of your view

for (UIView *view in yourView.subviews)
{
   if([view isKindOfClass:[UILabel class]] )
    {
      UILabel *label = (UILabel*)view;
      label.textColor = [UIColor greenColor];
    }
  //Similarly you can check and change for UIButton , All UI Elements
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Fawad Masud
  • 12,219
  • 3
  • 25
  • 34
0

You can do it using either of following ways:

  1. By setting UIAppearance in UILabel and UIButton in AppDelegate class, check link. OR
  2. By creating subclass of UILabel and UIButton.

I prefer the first one:

- (BOOL)application : (UIApplication *)application didFinishLaunchingWithOptions : (NSDictionary *)launchOptions
{
    //This color will affect every label in your app
     [[UIButton appearance] setTintColor:[UIColor redColor]]; 
    [[UILabel appearance] setTextColor:[UIColor redColor]]; 
    return YES;
}
Community
  • 1
  • 1
Sujay
  • 2,510
  • 2
  • 27
  • 47
0

you get all the subviews then you cast them based on their type after that you change their color

let subviews = view.subviews
        
        for v in subviews{
            if v is UILabel {
                let currentLabel = v as! UILabel
                currentLabel.textColor = UIColor.white
            } else if v is UIButton {
                let currentButton = v as! UIButton
                currentButton.setTitleColor(UIColor.white, for:.normal)
            }
        }

here I have changed the color for both UIbuttons and UILabels to white

R0b0t0
  • 390
  • 6
  • 20