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)
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
}
}
}