MadProgrammer MadProgrammer - 4 years ago 155
Swift Question

UIImageView.appearance is overriding UISegmentedControl.appearance

I've been trying to use the appearance proxy API to apply some default colors to some controls, but I've run into a problem.

When I apply a tint color to

UISegmentedControl
using something like...

UISegmentedControl.appearance().tintColor = UIColor.red


It generates this...

Red Tint

All good, but when I add...

UIImageView.appearance().tintColor = UIColor.green


it changes to...

Green Tint

Just to be clear, I have BOTH this lines in my code

UISegmentedControl.appearance().tintColor = UIColor.red
UIImageView.appearance().tintColor = UIColor.green


It doesn't matter in what order I call them, the result is the same, the
UIImageView
properties override the
UISegmentedControl
s

I've spent over half a day trying to find a solution to this problem but can't seem to find anything that works.

Running Xcode 8.2, iOS 10, Swift 3

What am I doing wrong and how can I fix?

Answer Source

I am not sure about this, but I guess, UISegmentedControl uses UIImageView to create segments, i.e. the segments we see inside segmented control are UIImageViews and not UIViews. UISegmentedControl even has methods to setImage for a particular segment.

If above is true, we can use appearanceWhenContainedIn API of UIAppearance to set image view tint colour like this:

UIImageView.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).tintColor = UIColor.red
UIImageView.appearance().tintColor = UIColor.green
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download