Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a line as a selection indicator to a UITabbarItem in Swift

I wanna use a thick line at the bottom of a UITabbarItems as a selection indicator. Due to the fact that the App must work on different phone sizes, I cannot use a image as selection indicator. That's why I think I have to use Swift to do this. (The line has to be 1/3 of page width).

I tried to use UITabBarItem.appearance() but without success.

like image 680
Tobonaut Avatar asked Nov 12 '15 08:11

Tobonaut


2 Answers

Swift 3:

extension UIImage {
    func createSelectionIndicator(color: UIColor, size: CGSize, lineHeight: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(CGRect(origin: CGPoint(x: 0,y :size.height - lineHeight), size: CGSize(width: size.width, height: lineHeight)))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tabBar = self.tabBarController!.tabBar
    tabBar.selectionIndicatorImage = UIImage().createSelectionIndicator(color: UIColor.blue, size: CGSize(width: tabBar.frame.width/CGFloat(tabBar.items!.count), height: tabBar.frame.height), lineHeight: 2.0)
}
like image 113
Jessie Avatar answered Nov 16 '22 20:11

Jessie


You can do it with add custom image, that will be created in your code, to selectionIndicatorImage on your UITabBar object. For example you can create extension for UIImage class like this:

extension UIImage {
    func createSelectionIndicator(color: UIColor, size: CGSize, lineWidth: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(CGRectMake(0, size.height - lineWidth, size.width, lineWidth))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

And call it in your first loaded ViewController like this:

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tabBar = self.tabBarController!.tabBar
        tabBar.selectionIndicatorImage = UIImage().createSelectionIndicator(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height), lineWidth: 2.0)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

In this case result will be like this:

enter image description here

like image 21
Alexey Pichukov Avatar answered Nov 16 '22 21:11

Alexey Pichukov