By far I handled gradient in navigation bar in the following manner_
let gradient = CAGradientLayer()
let sizeLength = UIScreen.main.bounds.size.height * 2
let defaultNavigationBarFrame = CGRect(x: 0, y: 0, width: sizeLength, height: 64)
gradient.frame = defaultNavigationBarFrame
gradient.colors = [UIColor(hex:"92CF1F").cgColor, UIColor(hex:"79AB1B").cgColor]
UINavigationBar.appearance().setBackgroundImage(self.image(fromLayer: gradient), for: .default)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().clipsToBounds = false
if DeviceType.IS_IPAD{
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont .systemFont(ofSize: 24, weight: UIFontWeightLight), NSForegroundColorAttributeName: UIColor.white]
}
else
{
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont .systemFont(ofSize: 20, weight: UIFontWeightLight), NSForegroundColorAttributeName: UIColor.white]
}
UISearchBar.appearance().backgroundColor = UIColor.clear
But Now in iPhone X I have issue due to "64" as navigation bar height for gradient as below_
Please suggest a fix for this that can be dynamically used in each case.
Change the Bar Style A user changes the navigation bar's style, or UIBarStyle , by tapping the “Style” button to the left of the main page. This button opens an action sheet where users can change the background's appearance to default, black-opaque, or black- translucent.
Use gradients as color fills that blend smoothly from one color to another. Use a CSS gradient anywhere that you can use an image, such as for the background of an element, an element border, or a mask.
Using Alisson Barauna's answer to your question, I managed to fix this issue by just updating my UINavigationBar extension to look like this:
extension UINavigationBar {
@objc func setGradientBackground(colors: [UIColor]) {
var updatedFrame = bounds
if UIDevice().userInterfaceIdiom == .phone {
if UIScreen.main.nativeBounds.height == 2436{
updatedFrame.size.height += 44
} else {
updatedFrame.size.height += 20
}
}
let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)
setBackgroundImage(gradientLayer.createGradientImage(), for: UIBarMetrics.default)
}
By doing this the height will just be set to the larger iPhone X size (44), if the program detects that an iPhone X is being used (as the screen height is 2436).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With