iOS : How to add Underline in UITabBarItem

Malav Soni picture Malav Soni · Sep 19, 2015 · Viewed 7.4k times · Source

I am working in a application where i need to add underline in UITabbarItem.

so i would like to add underline under the selected UITabbarItem in Default UITabbarcontroller of iOS.

I have already created subclass of UITabbarcontroller but didn't find any way to add line in that.

I want to do something like below image.

UITabbarWithUnderline Image

If anyone have any idea for this please share here.

Answer

ajay_nasa picture ajay_nasa · Feb 28, 2017

Code for Swift 3

In didFininshLaunch call method:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UITabBar.appearance().selectionIndicatorImage = getImageWithColorPosition(color: UIColor.blue, size: CGSize(width:(self.window?.frame.size.width)!/4,height: 49), lineSize: CGSize(width:(self.window?.frame.size.width)!/4, height:2))
        return true
    }

Method:

func getImageWithColorPosition(color: UIColor, size: CGSize, lineSize: CGSize) -> UIImage {
        let rect = CGRect(x:0, y: 0, width: size.width, height: size.height)
        let rectLine = CGRect(x:0, y:size.height-lineSize.height,width: lineSize.width,height: lineSize.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.clear.setFill()
        UIRectFill(rect)
        color.setFill()
        UIRectFill(rectLine)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }