iosswiftuiimageuitabbar

How can I change the color of the UITabBar top border by creating a UIImage programmatically?


From my understanding, the only way to change the color of the top border is to set the background image (320x49, with pixel line at top). It seems to me that this is the only way (please correct me if I'm wrong).

Is there a way to do this without using an image file? For example, someone helped me change the NavigationBar bottom border by creating a UIImage from code:

UINavigationBar.appearance().shadowImage = UIImage.colorForNavBar(UIColor.redColor())

extension UIImage {   
    class func colorForNavBar(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

This solution actually works well; it changes the color of my bottom border.

I tried to apply this to the TabBar, but nothing changes at all.

UITabBar.appearance().shadowImage = UIImage.colorForNavBar(.redColor())


Solution

  • You've pretty much answered your own question. You can do the same thing with your UITabBar as you did with your UINavigationBar. If you want to change the shadow image (i.e. the "top border"), then you have to change the background image. Straight from Apple:

    The custom shadow image for the tab bar. This attribute is ignored if the tab bar does not also have a custom background image. To set this attribute programmatically, use the shadowImage property.

    In your own question you seem to be aware of this:

    the only way to change the color of the top border is to set the background image (320x49, with pixel line at top)

    Except that it's not the background image that has a line at the top. You just have to set the background image to anything, then you can set the shadow image to your preference.

    If you open up the simple "tabbed application" template within Xcode, you'll find that adding these two lines of code (and your UIImage extension code) indeed work:

    // White background with red border on top
    UITabBar.appearance().backgroundImage = UIImage.colorForNavBar(.whiteColor())
    UITabBar.appearance().shadowImage = UIImage.colorForNavBar(.redColor())
    

    Tab Bar