0

I want to align the tab bar item images in my tab bar. I know I can do it in IB which I did and it worked. However I want to do it programatically. I'm trying to do it in AppDelegate. Following is my code which doesn't work. Can anyone point me what I'm doing wrong?

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "RootTabBarController") as! UITabBarController

let tabArray = tabBarController.tabBar.items as NSArray?
let homeTabItem = tabArray?.object(at: 0) as! UITabBarItem
homeTabItem.imageInsets = UIEdgeInsetsMake(12.0, 0.0, -12.0, 0.0)
Matt
  • 175
  • 1
  • 4
  • 20

1 Answers1

1

Access the tabbaritem view and now change according to your need . eg I need to set height width of image So I did it underneath:

class Tabbar: UITabBarController,UITabBarControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

  //  self.tabBarController?.selectedIndex = 2
    for tabBarItem in (self.tabBar.items)!{

        let viewTabBar = tabBarItem.value(forKey: "view") as? UIView

        let  imgView = viewTabBar?.subviews[0] as? UIImageView
        viewTabBar?.origin.y  = 6
        imgView?.frame.size.height = 24
        imgView?.frame.size.width = 24
        imgView?.clipsToBounds = true
        imgView?.contentMode = .scaleAspectFit
    }
}


override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    for tabBarItem in (self.tabBar.items)!{

        let viewTabBar = tabBarItem.value(forKey: "view") as? UIView
        let  imgView = viewTabBar?.subviews[0] as? UIImageView
        imgView?.frame.size.height = 24
        imgView?.frame.size.width = 24

        imgView?.clipsToBounds = true
        imgView?.contentMode = .scaleAspectFit
    }
}
}
Arnav
  • 638
  • 5
  • 14
  • Tx for help. viewTabBar?.origin.y = 6: origin is not a member of TabBarView and it crashes the app. Can you clarify on which file/view you insert above codes? I inserted first part in AppDelegate is that correct? Where to add override function? – Matt May 16 '18 at 20:24
  • I have edit my answer .Checkout the above class of tabbar controller. Aceess tabBar itenm in viewDidAppear. – Arnav May 17 '18 at 02:03
  • Tx it worked finally. But that origin still doesn't work. I think you are using older version. I manage to get the inset working by using the solution given here https://stackoverflow.com/questions/16285205/moving-uitabbaritem-image-down – Matt May 17 '18 at 21:10