Get global tint color from code

前端 未结 6 1130
眼角桃花
眼角桃花 2020-11-30 04:18

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条回答
  • 2020-11-30 04:41

    Swift 4.x:

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

    Usage:

    textField.textColor = .tintColor
    
    0 讨论(0)
  • 2020-11-30 04:43

    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.

    0 讨论(0)
  • 2020-11-30 04:45
    [UIApplication sharedApplication].keyWindow.tintColor;
    
    0 讨论(0)
  • 2020-11-30 04:52

    In the app delegate you can set it by

    UIColor *globalTint = [[[UIApplication sharedApplication] delegate] window].tintColor;
    
    0 讨论(0)
  • 2020-11-30 04:52

    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.

    0 讨论(0)
  • 2020-11-30 04:54
    [UIApplication sharedApplication].delegate.window.rootViewController.view.tintColor
    

    Seems to work.

    0 讨论(0)
提交回复
热议问题