我想在标签栏中对齐标签栏项目图像。我知道我可以在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)

最佳答案

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

关于ios - 通过在AppDelegate中访问选项卡栏项目来更改选项卡栏项目图像插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50359988/

10-10 20:47