首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用UINavigationBar使UIAppearance具有梯度背景

使用UINavigationBar使UIAppearance具有梯度背景
EN

Stack Overflow用户
提问于 2017-09-27 15:51:46
回答 1查看 346关注 0票数 0

按照this的问题,我可以为UINavigationBar设置一个背景梯度,但是当我试图通过UIAppearance设置它时,应用程序会在didFinishLaunching中崩溃,因为没有当前的CGContext。我如何才能在应用程序委托中保留我所有的UIAppearance代码呢?

return true之前在didFinishLaunching中调用的代码

代码语言:javascript
复制
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)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-27 16:47:37

调用UIGraphicsBeginImageContext时,必须提供非零CGRect。在我的例子中,我将框架设置为UINavigationBar.appearance().bounds,这是应用程序委托中的零rect。为了解决这个问题,我简单地将梯度frame设置为CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46452224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档