使用 UIAppearance 使 UINavigationBar 具有渐变背景

Make UINavigationBar have a gradient background using UIAppearance

根据 this 问题,我可以为 UINavigationBar 制作背景渐变,但是当我尝试通过 UIAppearance 设置它时,应用程序崩溃 didFinishLaunching因为没有电流CGContext。我怎样才能解决这个问题并在应用程序委托中保留我所有的 UIAppearance 代码?

didFinishLaunchingreturn true 之前调用的代码:

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)
}

调用UIGraphicsBeginImageContext时,您必须提供一个非零的CGRect。在我的例子中,我将框架设置为 UINavigationBar.appearance().bounds,这是应用程序委托中的零矩形。为了解决这个问题,我只需将渐变 frame 设置为 CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1)