Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UILabel's textColor in whole app using Swift

Tags:

ios

uilabel

swift

Is there any way in Swift i can change my UILabel's text color property at once in whole app? I've tried using appeareance property but that doesn't work for UILabel textColor. Any way or any library that works on the same.

like image 418
Rohitax Rajguru Avatar asked Jan 05 '19 11:01

Rohitax Rajguru


People also ask

How do I change the color of my UILabel Swift?

The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color. The only way I could change the text color programmatically was by using the standard colors, UIColor.

How do I change the UILabel text in Swift?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

How do I change the text field color in Swift?

Select the text field -> click "identity inspector" icon -> click on Plus button "user Defined runtime attributes" -> add this text "_placeholderLabel. textColor" in "key path" field -> choose the "Type" "color" and set the value color.

How do I change text color in Xcode?

There should be a text color box in interface builder, but you can also do it through code. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)] label. textColor = [UIColor redColor]; Or just use the reference that you already have to the text label.


1 Answers

I really liked Arash Etemad's solution, but found it quite extreme as it overrode ALL colours, even if some of them were customised. That's not great when working on an existing large project.

So I came up with this (Swift 5.2):

extension UILabel {

    override open func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)

        guard newSuperview != nil else {
            return
        }

        if #available(iOS 13.0, *) {
            if textColor == UIColor.label {
                textColor = .red
            }
        } else if textColor == UIColor.darkText {
            textColor = .red
        }
    }    
}

It uses the labels own lifecycle event to override default system font colour. With the appearance of dark mode in iOS 13, that can be identified as UIColor.label, whereas before it's UIColor.darkText.

This prevents a custom font colour from being overriden (unless your custom colour is the same as the default ?!? ), whilst not requiring to manually set font colour all over the project.

like image 165
Alex Ioja-Yang Avatar answered Oct 13 '22 21:10

Alex Ioja-Yang