【发布时间】:2013-09-28 09:54:05
【问题描述】:
我们如何通过代码改变iOS7/iOS8上的全局色调?我想更改使用此属性的多个对象,但不更改每个对象,这就是我想使用全局 tint 属性的原因。
【问题讨论】:
-
我知道您指定了“按代码”,不过,我认为重要的是要提一下情节提要的文件检查器中有一个全局 tint 属性
我们如何通过代码改变iOS7/iOS8上的全局色调?我想更改使用此属性的多个对象,但不更改每个对象,这就是我想使用全局 tint 属性的原因。
【问题讨论】:
只需在您的应用程序委托中更改 UIWindow 的 tintColor,它就会自动默认传递给它的所有 UIView 后代。
[self.window setTintColor:[UIColor greenColor]];
【讨论】:
UIView 上实现,因此您可以在视图层次结构中的任何视图上设置它,并且它的所有后代都将继承相同的默认 tintColor(除非您另外指定)
if([window respondsToSelector:@selector(setTintColor:)])
[[UIView appearance] setTintColor:[UIColor greenColor]];
【讨论】:
UIView 的tintColor 没有UI_APPEARANCE_SELECTOR 注释。这个答案是错误的。
UIAppearance 在 iOS 5 中被引入作为处理全局颜色(以及更多)的一种方式,但随后在 iOS 7 中,Apple 将 tintColor 移动到 UIView 并使其传播到子视图。在iOS 7 UI Transition Guide Apple 中声明:“iOS 7 不支持使用外观代理 API 设置 tintColor 属性。”但它似乎仍然有效。
【讨论】:
UIWindow 的 tintColor 属性或您建议的全局色调的影响。
self.window?.tintColor = UIColor(netHex: 0xc0392b) 起作用了。
您可以通过设置窗口的 tint 属性为整个应用程序指定色调颜色。为此,您可以使用类似于以下的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.tintColor = [UIColor purpleColor];
return YES;
}
【讨论】:
为 Swift 2.2 更新
你可以在任何地方这样做:
// Get app delegate
let sharedApp = UIApplication.sharedApplication()
// Set tint color
sharedApp.delegate?.window??.tintColor = UIColor.green()
或者,如果您尝试从 AppDelegate 执行此操作,
self.window?.tintColor = UIColor.green()
【讨论】:
为 Swift 5 更新
在 App Delegate 中写入:
self.window?.tintColor = UIColor.green
【讨论】:
以下事情对我不起作用:
navigationItem.backBarButtonItem?.tintColor = Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR
navigationItem.backBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR], for: .normal)
self.navigationController?.navigationBar.barStyle = UIBarStyle.black
navigationController?.navigationBar.barTintColor = Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR
navigationController?.navigationBar.tintColor = Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR]
以下工作:
或
对于整个应用程序:
let sharedApp = UIApplication.sharedApplication()
sharedApp.delegate?.window??.tintColor = UIColor.green()
对于特定控制器:
在初始化时设置窗口的色调颜色,并在取消初始化时设置应用程序的默认色调。
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
let window = UIApplication.shared.windows.first
window?.tintColor = Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR
}
required init?(coder: NSCoder) {
super.init(coder: coder)
let window = UIApplication.shared.windows.first
window?.tintColor = Theme.light.healthKit.BACK_BUTTON_TITLE_COLOR
}
deinit {
let window = UIApplication.shared.windows.first
window?.tintColor = Theme.light.App.DEFAULT_TINT_COLOR
}
【讨论】: