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?
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.
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
}
You can do it using either of following ways:
UIAppearance in UILabel and UIButton in AppDelegate class, check link. ORUILabel 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;
}
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