繁体   English   中英

第二次选择UITabBarItem时关闭以前的ViewController

[英]Dismiss previous ViewController upon selecting UITabBarItem for second time

我在一个iOS应用程序上工作,该应用程序实现了带有5个图标的UITabBarController。 整个项目通过Storyboard完成。 当我想为用户提供4个主题的选项时,我在静态tableView中做了什么,所以遇到了一个问题。

当用户更改主题时,先前通过tabBar视图控制器实例化的对象不会更新为主题更改,因为它们存在于主题更新之前。 我能以某种方式关闭它们,并在UITabBar委托的didSelect方法上创建相同视图控制器类的新实例吗?

我是否正确解决了这个问题? 任何帮助将非常感激!

预先感谢您的帮助。

类MainTabController:UITabBarController {

override func viewDidLoad()
{
    super.viewDidLoad()
}



override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)
{
    let theme = UserDefaults.standard.string(forKey: "selectedColor")
    print(theme!)
    for vc in self.viewControllers!
    {


        if (theme == "default")
        {
            vc.view.backgroundColor = UIColor(red: 0xF9 , green: 0xF7 , blue: 0xF7)

        }else if (theme == "theme1")
        {
            vc.view.backgroundColor = UIColor(red: 0x1F , green: 0xFF, blue: 0xFF)

        }else if (theme == "theme2")
        {
            vc.view.backgroundColor = UIColor(red: 0xE3 , green: 0xFD, blue: 0xFD)

        }else if (theme == "theme3")
        {
            vc.view.backgroundColor = UIColor(red: 0x3E, green: 0xC1, blue: 0xD3)
        }

    }

}

}

在每个视图控制器中实现的示例:

override func viewDidLoad()
{
    let theme = UserDefaults.standard.string(forKey: "selectedColor")
    print(theme!)
    if (theme == "default")
    {
        outerView.backgroundColor = UIColor(red: 0xF9 , green: 0xF7 , blue: 0xF7)

    }else if (theme == "theme1")
    {
        outerView.backgroundColor = UIColor(red: 0x1F , green: 0xFF, blue: 0xFF)

    }else if (theme == "theme2")
    {
        outerView.backgroundColor = UIColor(red: 0xE3 , green: 0xFD, blue: 0xFD)

    }else if (theme == "theme3")
    {
        outerView.backgroundColor = UIColor(red: 0x3E, green: 0xC1, blue: 0xD3)
    }
}

didSelect内部,您可以访问选项卡VC并根据需要进行更改(在选项卡中的任何VC内)

for vc in self.tabBarController!.viewControllers! {

   vc.view.backgroundColor = UIColor.red

  // if you want to set a property 

  if let other  = vc as? OtherViewController {
     // change here 
  }  

}

//

如果要在tabBar自定义类中使用此代码

 for vc in self.viewControllers! {

   vc.view.backgroundColor = UIColor.red

  // if you want to set a property 

  if let other = vc as? OtherViewController {
     // change here 
  }  

}

//

编辑后,您需要创建一个包含externalView的协议并在每个VC中都遵循此协议,或者强制转换为VC并更改其属性

创建自定义的UITabBarController类,并在其viewDidLoad添加:

for vc in self.viewControllers! {

   vc.view.backgroundColor = .....

}  

现在,将此自定义类链接到Storyboard的UITabBarController

更新:

您从UserDefaults错误获取值。

UserDefaults.standard.string(forKey: "selectedColor")  

它应该是 :

UserDefaults.standard.object(forKey: "selectedColor")

解决我的问题的方法非常简单,但是经过数小时的搜索!

我必须将所有用于编辑视图的代码而不是viewDidLoad放在viewDidAppear中,因为viewDidLoad仅在第一次运行时才与viewDidAppear相对,后者在用户每次按下此特定选项卡时都会调用。

谢谢大家的快速回答!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM