如果我将所有按钮全局更新为相同的颜色,我不希望键盘上的按钮更改颜色。如何手动控制以重置为原始颜色?
[[UIApplication sharedApplication] delegate].window.tintColor = [Helper getColor:color];
[[UIButton appearance] setBackgroundColor:[Helper getColor:color]];
您可以使用以下方法定义哪些视图/类应遵守UIAppearance
规则:
+ (instancetype)appearanceWhenContainedInInstancesOfClasses:(NSArray<Class<UIAppearanceContainer>> *)containerTypes;
现在可能有几种方法可以做到,这只是其中一种。如果您想回答,可以跳到最后,但我提供了更多信息,以了解为什么以及如何好奇。
请记住,您传递的数组不是您要外观代理工作的所有位置的列表,如果在同一列表中传递多个位置,它将被评估为第一个元素嵌套最多的层次结构。
又名
[UIButton appearanceWhenContainedInInstancesOfClasses:@[[MyView class], [UITableView class]]]
表示仅将规则应用于MyView
内部和UITableView
内部的按钮。
另一个要理解的好事是如何评估规则。UIKit
将始终首先检查最长的层次结构。并且它将始终开始检查最外面的对象(在大多数情况下,例如UIViewController
)。
外观将应用于匹配的第一个层次结构。
AKA
UILabel.appearance(whenContainedInInstancesOf: [CustomView.self]).textColor = red;
UILabel.appearance(whenContainedInInstancesOf: [UIViewController.self]).textColor = UIColor.gray;
[这意味着您的所有标签都将显示为灰色,因为它开始检查最外面的对象UIViewController
,并且由于匹配,它不再进一步检查。
但是因为首先评估更长的层次结构:
UILabel.appearance(whenContainedInInstancesOf: [CustomView.self, UIViewController.self]).textColor = red;
UILabel.appearance(whenContainedInInstancesOf: [UIViewController.self]).textColor = UIColor.gray;
手段标签将按预期在CustomView
上显示为红色,因为第一行的层次结构中包含两个元素,这意味着将在所有元素层次结构(如第二行)之前对其进行检查。
因此,我们要做的就是在键盘窗口堆栈中的某个位置找到父视图或视图控制器-并在其上设置透明的背景颜色...
除了检查了键盘窗口的整个层次结构之外,每个控制器和导致这些按钮的视图都是私有的:(我检查了从UIRemoteKeyboardWindow开始的每个视图的右侧显示的类层次结构。它们都是私有的)
由于我们无法触碰到更少选择的系统类-我们必须设置仅适用于我们主应用程序窗口的UIWindow
或UIViewControllers
的规则。
我可以想象一个解决方案,其中有一个名为UIViewController
的自定义BaseController
类,我的所有VC都继承自该类。..但这似乎很烦人。为什么我们不创建在我们自己的应用程序中使用的自定义UIWindow
类呢?
// internal and final just included for compiler optimizations, not necessary
internal final class MyWindow: UIWindow {}
@UIApplicationMain
internal final class AppDelegate: UIResponder, UIApplicationDelegate {
lazy var appWindow: UIWindow = {
return MyWindow(frame: UIScreen.main.bounds)
}()
...
// then wherever you're setting the key window make sure you use your custom one
appWindow.rootViewController = vc
appWindow.makeKeyAndVisible()
现在您可以将规则应用于MyWindow
:
[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[MyWindow class]]]
setBackgroundColor:[Helper getColor:color]];
((您应该对色调有所了解,因为您将其写为bc已经只影响正在使用该应用程序的窗口)