【问题标题】:Change Tab Bar Item Image inset by accessing Tab Bar Items in AppDelegate通过访问 AppDelegate 中的 Tab Bar Items 更改 Tab Bar Item Image inset
【发布时间】:2018-10-25 20:45:47
【问题描述】:

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

【问题讨论】:

    标签: ios storyboard tabbar uitabbaritem swift4.1


    【解决方案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
        }
    }
    }
    

    【讨论】:

    • Tx 寻求帮助。 viewTabBar?.origin.y = 6:origin 不是 TabBarView 的成员,它会使应用程序崩溃。你能澄清一下你在上面的代码中插入了哪个文件/视图吗?我在 AppDelegate 中插入了第一部分,对吗?在哪里添加覆盖功能?
    • 我已经编辑了我的答案。检查上面的标签栏控制器类。在 viewDidAppear 中访问 tabBar 项。
    • Tx 终于成功了。但是那个起源仍然不起作用。我认为您使用的是旧版本。我设法通过使用此处给出的解决方案stackoverflow.com/questions/16285205/… 使插图工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2014-09-22
    • 2019-02-25
    • 2022-10-16
    相关资源
    最近更新 更多