我有一个标签栏 Controller (带有底部菜单)和一个顶部菜单。问题是我不想将黄色和绿色 View 链接到选项卡栏(因为用户将使用顶部菜单而不是底部菜单更改 View )。
我遇到一个问题,每次单击按钮时,都会堆叠一个新的 View 实例(所以我最终得到类似 V1 -> V2 -> V3 -> V2 -> V4 等等的东西)
我的部分解决方案是制作这样的东西:
@IBAction func yellowViewButtonAction(_ sender: AnyObject)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "YelloViewController") as! YelloViewController
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
// some process
if viewController is YelloViewController {
print("View is on stack")
}
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "YelloViewController") as! YelloViewController
self.navigationController?.pushViewController(controller, animated: false)
}
}
我可以看到 View 在导航堆栈上,因为 for
中的 if
语句为 true
。问题是,我如何检索它而不是推送同一 View 的新实例? (因为除了这个存在的巨大内存问题之外,我还丢失了 View 上的所有数据)。
我想保持堆栈中的所有内容完好无损。
例子:
V1 -> V2 -> V3 -> V4(当前 View )
如果我从 V4 回到 V1,我仍然希望导航 Controller 堆栈上有 V4、V3 和 V2。
另一个问题是,如果这种解决方案是 Apple 可能会拒绝的。
感谢任何帮助。
最佳答案
看起来您不使用也不需要导航 Controller 。每当您调用 self.navigationController?.pushViewController(controller, animated: false)
时,该 Controller 的一个新实例就会进入堆栈。
理想情况下,您会从导航到的 View Controller 调用 popViewController。在创建标签栏 Controller 的自定义行为时,很难完全按照您的计划获得导航逻辑,至少在我看来是这样。
在这种情况下,我通常会手动处理显示和隐藏 View Controller 。
@IBAction func didPressTab(sender: UIButton) {
let previousIndex = selectedIndex
selectedIndex = sender.tag
buttons[previousIndex].selected = false
let previousVC = viewControllers[previousIndex]
previousVC.willMoveToParentViewController(nil)
previousVC.view.removeFromSuperview()
previousVC.removeFromParentViewController()
sender.selected = true
let vc = viewControllers[selectedIndex]
addChildViewController(vc)
vc.view.frame = contentView.bounds
contentView.addSubview(vc.view)
vc.didMoveToParentViewController(self)
}
每个“导航按钮”都有唯一的 ID 并调用 didPressTab 函数。
我实际上是从本教程中学到的:https://github.com/codepath/ios_guides/wiki/Creating-a-Custom-Tab-Bar
关于ios - 显示一个已经在 Navigation Stack 上的 View Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593356/