-1

I use this code to create gradient color for my navigation bar:

extension UINavigationBar 
{
    /// Applies a background gradient with the given colors
    func apply(gradient colors : [UIColor]) {
        var frameAndStatusBar: CGRect = self.bounds
        frameAndStatusBar.size.height += 20 // add 20 to account for the status bar

        setBackgroundImage(UINavigationBar.gradient(size: frameAndStatusBar.size, colors: colors), for: .default)
    }

    /// Creates a gradient image with the given settings
    static func gradient(size : CGSize, colors : [UIColor]) -> UIImage?
    {
        // Turn the colors into CGColors
        let cgcolors = colors.map { $0.cgColor }

        // Begin the graphics context
        UIGraphicsBeginImageContextWithOptions(size, true, 0.0)

        // If no context was retrieved, then it failed
        guard let context = UIGraphicsGetCurrentContext() else { return nil }

        // From now on, the context gets ended if any return happens
        defer { UIGraphicsEndImageContext() }

        // Create the Coregraphics gradient
        var locations : [CGFloat] = [0.0, 1.0]
        guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: cgcolors as NSArray as CFArray, locations: &locations) else { return nil }

        // Draw the gradient
        context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: size.width, y: 0.0), options: [])

        // Generate the image (the defer takes care of closing the context)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

to use:

self.navigationController?.navigationBar.apply(gradient: [
    .red,
    .green,
    .blue
])

But it works if I have the default navigation bar size. But when my navigation bar is large my code doesn't work(I see default white color). I want it to be the other way around. When the navigation bar is large, it is colored with a gradient. When the navigation bar is default size (for example when scrolling down) then its color is white as default

User
  • 121
  • 1
  • 2
  • 11
  • Does this help? https://stackoverflow.com/questions/46196848/custom-background-image-with-large-titles-navigationbar-in-ios-11 – DonMag Aug 07 '23 at 14:28
  • @DonMag No. If I use image like this https://stackoverflow.com/a/46446178/14207208 Everything works fine in portrait orientation. But in landscape, when I scroll the navigation bar up, it doesn't stretch like it does in portrait. When I try to stretch I see a white background between my content and the navigation bar. – User Aug 07 '23 at 15:58
  • Are you asking how to get the automatic expand/shrink navigation bar in landscape mode? – DonMag Aug 07 '23 at 18:03

0 Answers0