Tuesday, March 31, 2015

Gradient UINavigationBar in Swift

Here's how to make a gradient NavBar in Swift, taken mainly from this <a href="http://stackoverflow.com/questions/494982/uinavigationbar-tintcolor-with-gradient">SO post</a>: First create an extension for CAGradientLayer Here's how to make a gradient NavBar in Swift:
First create an extension for CAGradientLayer (need to add Quartz library)
extension CAGradientLayer {
    class func gradientLayerForBounds(bounds: CGRect) -> CAGradientLayer {
        var layer = CAGradientLayer()
        layer.frame = bounds
        layer.colors = [UIColor.redColor().CGColor, UIColor.blueColor().CGColor]
        return layer
    }
}
Use whatever colors suit your needs.
Then in your overriden NavController class (so many ways to do this, I chose to set it up in the NavController subclass used everywhere in my app),
private func imageLayerForGradientBackground() -> UIImage {

    var updatedFrame = self.navigationBar.bounds
    // take into account the status bar
    updatedFrame.size.height += 20
    var layer = CAGradientLayer.gradientLayerForBounds(updatedFrame)
    UIGraphicsBeginImageContext(layer.bounds.size)
    layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
In your viewDidLoad of the NavController subclass:
override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationBar.translucent = false
        self.navigationBar.tintColor = UIColor.whiteColor()
        let fontDictionary = [ NSForegroundColorAttributeName:UIColor.whiteColor() ]
        self.navigationBar.titleTextAttributes = fontDictionary
        self.navigationBar.setBackgroundImage(imageLayerForGradientBackground(), forBarMetrics: UIBarMetrics.Default)
    }
I did some whitening to the tint and title text, mainly because any gradient you have, white would probably work best.
Here's the current app I'm working on with the gradient colors of my choice:

5 comments:

  1. Crystal clear, i've been searching this for a while, really helpful.

    ReplyDelete
  2. What should I do to make the gradient go from left to right?

    ReplyDelete
    Replies
    1. That's a good question, I'll have to try a few things out to see if I can get it working, if you figure it out, post it here and I'll update the post.

      Delete
    2. To change the direction (you can also set it to an angle), use:
      layer.startPoint = CGPointMake(0.0. 1.0)
      layer.endPoint = CGPointMake(1.0, 0.0)
      Simply adjust the CGPoints to meet your needs.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete

Mvvm on Mobile?

Here's my talk from Houston Tech Fest 2017. Recorded Talk: Slides: https://speakerdeck.com/markawil/mvvm-and-mobile-dont-do-it...