我在一个 iOS 应用程序上工作,该应用程序实现了一个连接了 5 个图标的 UITabBarController。整个项目是通过 Storyboard 制作的。当我想为用户提供 4 个主题的选项时,我在静态 tableView 中做了这件事,我遇到了一个问题。
当用户更改主题时,先前通过 tabBar View Controller 实例化的 View Controller 不会更新到主题更改,因为它们在主题更新之前存在。我可以以某种方式关闭它们并在 UITabBar 委托(delegate)的 didSelect 方法上创建相同 View Controller 类的新实例吗?
我是否正确地处理了这个问题?任何帮助将不胜感激!
预先感谢您的帮助。
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)
}
}
}
}
在每个 View Controller 中实现的示例:
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
}
}
//
编辑后,您需要创建一个包含 outerView 的协议(protocol)并在每个 VC 中遵守此协议(protocol),或者强制转换为 VC 并更改其属性
关于ios - 第二次选择 UITabBarItem 时关闭之前的 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361886/