通过访问AppDelegate中的选项卡栏项来更改选项卡栏项目图像插入

时间:2018-05-15 22:25:32

标签: ios storyboard tabbar uitabbaritem swift4.1

我想在标签栏中对齐标签栏项目图片。我知道我可以在IB做到这一点我做了并且有效。但是我想以编程方式进行。我正试图在AppDelegate中做到这一点。以下是我的代码不起作用。 谁能指出我做错了什么?

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)

1 个答案:

答案 0 :(得分:1)

访问tabbaritem视图,现在根据需要进行更改。例如,我需要设置图像的高度宽度所以我在下面做了:

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