Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling navigation bar background gradient in iPhone X

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_

enter image description here

Please suggest a fix for this that can be dynamically used in each case.

like image 998
Piyush Mathur Avatar asked Sep 22 '17 09:09

Piyush Mathur


People also ask

How do I change the navigation bar on my Iphone?

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.

What is Gradient Iphone?

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.


1 Answers

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).

like image 116
Simba Avatar answered Nov 15 '22 02:11

Simba