0

I'm passing my UIKit app to SwiftUI and struggle to make this work.

I want to put a left to right gradient on each navigation bars of my double column iPad display.

I've tried various approach but never quite make it.

lorenzo
  • 1,487
  • 1
  • 17
  • 25

1 Answers1

2

Using FRIDDAY's answer from How change background color if using NavigationView in SwiftUI?, I achieved the much appreciated gradient:

extension UINavigationController {
    
    override open func viewDidLoad() {
        
        super.viewDidLoad()
        
        let gradient = CAGradientLayer()
        
        gradient.frame = self.view.bounds
        gradient.colors = [UIColor(Colors.red).cgColor, UIColor(Colors.orange).cgColor]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        
        let standard = UINavigationBarAppearance()
        standard.backgroundImage = gradient.toImage()

        let compact = UINavigationBarAppearance()
        compact.backgroundImage = gradient.toImage()

        let scrollEdge = UINavigationBarAppearance()
        scrollEdge.backgroundImage = gradient.toImage()

        self.navigationBar.standardAppearance = standard
        self.navigationBar.compactAppearance = compact
        self.navigationBar.scrollEdgeAppearance = scrollEdge
        
    }
    
}

extension CALayer {

    func toImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        self.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage!
    }
    
}
lorenzo
  • 1,487
  • 1
  • 17
  • 25
  • 1
    What's the toImage() functin you're using on the gradient ? – C0D3 Sep 27 '21 at 05:52
  • Ok I guess you have something like this: import Foundation import QuartzCore import UIKit extension CALayer { func toImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(frame.size, isOpaque, 0) render(in: UIGraphicsGetCurrentContext()!) let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage! } } – C0D3 Sep 27 '21 at 06:00
  • @lorenzo Could you add toImage function? – Brogrammer Jan 13 '23 at 04:36
  • 1
    @Santiago added in the answer! – lorenzo Jan 13 '23 at 08:53