2017-09-27 3 views
0

Après this question, je suis en mesure de faire un dégradé de fond pour un UINavigationBar, mais lorsque je tente de le régler par UIAppearance, les accidents d'application dans le didFinishLaunching parce qu'il n'y a pas CGContext actuelle. Comment puis-je contourner cela et toujours avoir tout mon code UIAppearance dans le délégué de l'application?Faire UINavigationBar ont un fond dégradé en utilisant UIAppearance

Le code étant appelé juste avant return true dans le didFinishLaunching:

private func setNavBarAppearance() { 
    let titleAttributes: [NSAttributedStringKey: Any] = [.foregroundColor: UIColor.white] 
    UINavigationBar.appearance().titleTextAttributes = titleAttributes 
    UINavigationBar.appearance().barTintColor = .white 
    UINavigationBar.appearance().tintColor = .white 
    UINavigationBar.appearance().makeTransparent() 

    // Set gradient 
    let colors = [UIColor.lavender.cgColor, UIColor.mint.cgColor] 
    let gradientLayer = CAGradientLayer() 
    gradientLayer.frame = UINavigationBar.appearance().bounds 
    gradientLayer.colors = colors 
    gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) 
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.5) 

    let image = UIImage(layer: gradientLayer) 
    UINavigationBar.appearance().setBackgroundImage(image, for: .default) 
} 
+0

C'est peut-être une meilleure solution pour vous juste de sous-classer 'UINavigationBar'. – the4kman

Répondre

0

Lorsque vous appelez UIGraphicsBeginImageContext, vous devez fournir une valeur non nulle CGRect. Dans mon cas, je mettais le cadre à UINavigationBar.appearance().bounds qui est un rect zéro dans le délégué de l'application. Pour contourner cela, j'ai simplement mis le dégradé frame à CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1)