How can I create a horizontal gradient background for my iOS nav bar?

前端 未结 4 532
难免孤独
难免孤独 2021-01-31 10:44

I know how to set a navigation bar background color (with barTintColor), but now I am working on an iOS app that calls for a horizontal gradient (not the typical vertical gradie

4条回答
  •  盖世英雄少女心
    2021-01-31 11:25

    Updated @JulianM answer for iOS 10 / swift 3.0:

    let gradientLayer = CAGradientLayer()
    var updatedFrame = self.navigationController!.navigationBar.bounds
    updatedFrame.size.height += 20
    gradientLayer.frame = updatedFrame
    gradientLayer.colors = [UIColor.green.cgColor, UIColor.blue.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    
    UIGraphicsBeginImageContext(gradientLayer.bounds.size)
    gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    self.navigationController!.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
    

提交回复
热议问题