【问题标题】:Make UINavigationBar have a gradient background using UIAppearance使用 UIAppearance 使 UINavigationBar 具有渐变背景
【发布时间】:2017-09-27 15:51:46
【问题描述】:

this 问题之后,我可以为UINavigationBar 制作背景渐变,但是当我尝试通过UIAppearance 设置它时,应用程序在didFinishLaunching 中崩溃,因为没有当前@987654325 @。我怎样才能解决这个问题,并且在应用程序委托中仍然拥有我所有的 UIAppearance 代码?

didFinishLaunching 中的return 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)
}

【问题讨论】:

  • UINavigationBar 子类化可能是更好的解决方案。

标签: ios swift uiappearance


【解决方案1】:

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

【讨论】:

  • 这太棒了,我来自 Xamarin.iOS,这是最好的方法。
猜你喜欢
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 2010-10-19
  • 2023-03-28
相关资源
最近更新 更多