Search code examples
iosswiftuinavigationbargradient

Swift NavigationBar gradient different than on view below


I have gradient on naviBar and View below but colours are displayed different. Somebody know why? I don't have extra tints on view.

code for naviBar:

func addGradientImageView(withColours: [UIColor] = [.amaranth, .dodgerBlue]) {
    let cgColours = withColours.map { $0.cgColor }
    let gradientLayer = CAGradientLayer()
    var updatedFrame = bounds
    updatedFrame.size.height += UIApplication.shared.statusBarFrame.height
    gradientLayer.frame = updatedFrame
    gradientLayer.colors = cgColours
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
    UIGraphicsBeginImageContext(gradientLayer.bounds.size)
    gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(image, for: UIBarMetrics.default)
}

code for view:

func applyHorizontalGradient(withColours: [UIColor] = [.amaranth, .dodgerBlue]) {
    let cgColours = withColours.map { $0.cgColor }
    let grad = CAGradientLayer()
    grad.startPoint = CGPoint(x: 0, y: 0)
    grad.endPoint = CGPoint(x: 1, y: 0)
    grad.frame = self.bounds
    grad.colors = cgColours
    self.layer.insertSublayer(grad, at: 0)
}

enter image description here

enter image description here


Solution

  • extension UIView {
    
    func applyGradientImage(withColours: [UIColor] = [.amaranth, .dodgerBlue],
                            startPoint: CGPoint = CGPoint(x: 0, y: 0),
                            endPoint: CGPoint = CGPoint(x: 1, y: 0)) {
        let imageView = ImageView()
        insertSubview(imageView, at: 0)
        imageView.expandToSuperviewSafearea(withoutBottomSafeArea: false)
        imageView.image = gradientImage(withColours: withColours, startPoint: startPoint, endPoint: endPoint)
    }
    }