UIImageView.appearance重写了UISegmentedControl.appearance

我一直在尝试使用外观代理API将一些默认颜色应用到某些控件,但我遇到了一个问题。

当我使用类似的东西将色调颜色应用于UISegmentedControl

 UISegmentedControl.appearance().tintColor = UIColor.red 

它产生了这个……

红色调

一切都很好,但是当我添加…

 UIImageView.appearance().tintColor = UIColor.green 

它改为……

绿色调

为了清楚起见,我的代码中有这两行

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

我调用它们的顺序无关紧要,结果是一样的, UIImageView属性覆盖UISegmentedControl s

我花了半天时间试图找到解决这个问题的方法,但似乎找不到任何有效的方法。

运行Xcode 8.2,iOS 10,Swift 3

我做错了什么,我该如何解决?

我不确定这一点,但我猜, UISegmentedControl使用UIImageView创建段,即我们在分段控件中看到的段是UIImageViews而不是UIViewsUISegmentedControl甚至还有针对特定段的setImage方法。

如果以上是真的,我们可以使用UIAppearance appearanceWhenContainedIn API来设置图像视图色调,如下所示:

 UIImageView.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).tintColor = UIColor.red UIImageView.appearance().tintColor = UIColor.green