【问题标题】:Gradient Layer in Navigation Bar in iOS 11iOS 11 导航栏中的渐变层
【发布时间】:2018-05-19 08:02:19
【问题描述】:

在导航栏中添加渐变层后,我在 iOS 11 上运行时看不到任何左右栏按钮项。但相同的代码在 iOS 10/9 上显示良好..

谁能提供你宝贵的建议来解决这个问题

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setUpGradientNavigationBar()
}

func setUpGradientNavigationBar() {

    let lightRedColor = UIColor(red: CGFloat(197/255.0), green: 47/255.0, blue: 40/255.0, alpha: 1.0).cgColor
    let mediumRedColor = UIColor(red: CGFloat(176/255.0), green: 42/255.0, blue: 36/255.0, alpha: 1.0).cgColor
    let darkRedColor = UIColor(red: CGFloat(106/255.0), green: 25/255.0, blue: 22/255.0, alpha: 1.0).cgColor
    let colors = NSArray(objects: lightRedColor, mediumRedColor, darkRedColor)

    let gradientLayer = getGradientLayerForColors(colors, location: 0.5, andFrame: self.navigationController?.navigationBar.bounds)

    self.navigationController?.navigationBar.barTintColor =  UIColor.black
    self.navigationController?.navigationBar.layer.insertSublayer(gradientLayer, at: 1)
    self.navigationController?.navigationBar.tintColor = UIColor.white

    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: nil, action: nil)

}

func getGradientLayerForColors(_ colors: NSArray, location:CGFloat, andFrame frame:CGRect?) -> CAGradientLayer {
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = colors as [AnyObject]
    gradientLayer.locations = [0.0,NSNumber.init(value: Float(location))]
    gradientLayer.frame = frame!
    return gradientLayer
}

【问题讨论】:

  • 我在 iOS 11.2 中尝试了你的代码并且它的工作原理。
  • @torap 谢谢先生。我浪费时间试图修复它,最后你把它钉牢了。 Xcode 以升级的名义推了很多 bug。
  • iOS 6 被调用,他们想要他们的导航栏回来。

标签: uinavigationbar uibarbuttonitem ios11 swift4 xcode9


【解决方案1】:

斯威夫特 5

  • 在渐变中包含状态栏。
  • 不使用图片。
  • 使用透明度,因此内容通过导航栏可见。
extension UINavigationBar {

    func addGradient(_ toAlpha: CGFloat, _ color: UIColor) {
        let gradient = CAGradientLayer()
        gradient.colors = [
            color.withAlphaComponent(toAlpha).cgColor,
            color.withAlphaComponent(toAlpha).cgColor,
            color.withAlphaComponent(0).cgColor
        ]
        gradient.locations = [0, 0.8, 1]
        var frame = bounds
        frame.size.height += UIApplication.shared.statusBarFrame.size.height
        frame.origin.y -= UIApplication.shared.statusBarFrame.size.height
        gradient.frame = frame
        layer.insertSublayer(gradient, at: 1)
    }

}

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 2018-03-12
    • 2018-01-03
    • 2018-05-08
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多