infernouk
infernouk

Reputation: 1137

Adding Separator to UINavigationBar - iOS

I noticed the apple clock app has a thin bar on its header that separates it nicely from the content and makes the interface look slightly 3D. I wanted to replicate this on my own navigation bar but can't see a way to do so? How would I achieve this

timer

my app

Upvotes: 1

Views: 2180

Answers (1)

Pranav Jaiswal
Pranav Jaiswal

Reputation: 3752

I've created an Extension on UINavigationBar to show or hide that separator line. By default I've noticed UINavigationBar has a separator by default.

extension UINavigationBar {

    func hideNavBarSeparator() {
        let image = UIImage()
        shadowImage = image
        setBackgroundImage(image, for: UIBarMetrics.default)
    }

    func showNavBarSeparator() {
        let img = UIImage.pixelImageWithColor(color: UIColor.red)
        shadowImage = img
    }
}

extension UIImage {
    class func pixelImageWithColor(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

Here is how to use it:

yourNavigationBar.hideNavBarSeparator()

yourNavigationBar.showNavBarSeparator()

Upvotes: 7

Related Questions