有没有办法从嵌入式 ViewController 更改 Tabbar 图像和操作?

Is there a way to change Tabbar images and action from embedded ViewController?

我有 5 个 ViewController 嵌入了 TabbarController。我创建了一个 class 标签栏来自定义我的标签栏,例如:

class Tabbar: UITabBarController,UITabBarControllerDelegate {

var tabBarIteam = UITabBarItem()

@IBOutlet weak var tabbar: UITabBar!

 override func viewDidLoad() {

     super.viewDidLoad()
                        // THIS IS FOR FİRST TABBAR ITEM
   let selectedImage1 = UIImage(named: "vitrin_active")?.withRenderingMode(.alwaysOriginal)
    let deSelectedImage1 = UIImage(named: "vitrin_deactive")
           tabBarIteam = self.tabBar.items![0]
           tabBarIteam.image = deSelectedImage1
           tabBarIteam.selectedImage = selectedImage1

  .... I HAVE ALSO 4 MORE.
}

在我的第一个ViewController中,有一个按钮动作

    @IBAction func ChangeTabbarimageAndAction(_ sender: Any) {
    ..
}

我想在点击 FirstView 的 ChangeTabbarimageAndAction 时更改 Tabbar 图像和操作(如推送)。这可能吗?如果是,我该怎么做?我在 SO 中搜索但找不到任何解决方案。

如果您想更改当前 UIViewController 的标签栏图像或标题,您可以从 UIViewController 访问 tabBarItem 并可以像这样更改它的属性:

@IBAction func ChangeTabbarimageAndAction(_ sender: Any) {
    tabBarItem.image = UIImage(named: "New Image name")
    tabBarItem.selectedImage = UIImage(named: "NewSelectedImageName")
    tabBarItem.title = "New Title"
}

您可以在 tabbar 的委托方法中更改操作

 class yourclass: UIViewController, UITabBarDelegate {
        func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
            print("push or present action")
        }
    }

您可以使用

来设置图像
 let firstViewController:UIViewController = UIViewController()
        // The following statement is what you need
        let customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME"), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))

        firstViewController.tabBarItem = customTabBarItem