Get global tint color from code

2019-01-07 11:29发布

Is there a way I can get the global tint color from my project by code? To avoid a misunderstanding I mean the global tint color, which i can set in the File Inspector.

6条回答
劫难
2楼-- · 2019-01-07 12:08

Swift 4.x:

extension UIColor {
    static var tintColor: UIColor {
        get {
            return UIApplication.shared.keyWindow?.rootViewController?.view.tintColor ?? .red
        }
    }
}

Usage:

textField.textColor = .tintColor
查看更多
Explosion°爆炸
3楼-- · 2019-01-07 12:09

Max's answer is correct, but I found out that you have to get the navigationController's window:

self.navigationController.view.window.tintColor = [UIColor redColor];

However, note that this wouldn't work if you have set the tintColor manually from Storyboard. The value from Storyboard will be used if you have done so. I've filed a bug with Apple on this. I think this code shouldn't be ignored even if we've set the tintColor from Storyboard.

查看更多
We Are One
4楼-- · 2019-01-07 12:14
[UIApplication sharedApplication].keyWindow.tintColor;
查看更多
等我变得足够好
5楼-- · 2019-01-07 12:16

Easy.

Objective C:

UIColor *tintColor = [[self view]tintColor];

Swift:

let tintColor = self.view.tintColor;

This should get the tintColor set on the app. If you change it, this property should get updated. This assumes you're inside a viewController or a subclass of one and that you haven't overridden the tintColor in some superView between this view and the window.

Update: Notice if you are attempting to get the tint color of a view controller that has not been added to the window then it will not have the custom tint color since this color is inherited from the window object. Thanx to @ManuelWa for pointing this out in the comments.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-07 12:17
[UIApplication sharedApplication].delegate.window.rootViewController.view.tintColor

Seems to work.

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-07 12:22

In the app delegate you can set it by

UIColor *globalTint = [[[UIApplication sharedApplication] delegate] window].tintColor;
查看更多
登录 后发表回答