[英]How can I find the selected tab in tab bar scheme from the child view controllers
[英]how can I manage controllers in Container View with using tab bar
在我的故事板上,我有主ViewController
,而不是TabBarViewController,它由底部的TabBar
,顶部的视图和中间的ContainerView
。 ContainerView
有一个NavigationController
。 我也有4个ViewControllers
,其中之一- RootViewController
的NavigationController
。 我希望在选择TabBarItem时显示其中一个ViewControllers
,将来我将添加幻灯片菜单,该菜单还将显示所选的ViewController。
我有下一个代码,该代码仅显示ContainerView内的初始ViewController,并且当我选择TabBarItems时,不显示新的ViewController,并且仅看到第一个View Controller。 怎么了?
class ViewController: UIViewController {
@IBOutlet weak var container: UIView!
@IBOutlet weak var first: UITabBarItem!
@IBOutlet weak var second: UITabBarItem!
@IBOutlet weak var third: UITabBarItem!
@IBOutlet weak var fours: UITabBarItem!
@IBOutlet weak var tabBar: UITabBar!
var firstVC: FirstViewController?
var secondVC: SecondViewController?
var thirdVC: ThirdViewController?
var foursVC: FoursViewController?
var navi: UINavigationController?
override func viewDidLoad() {
super.viewDidLoad()
tabBar.delegate = self
initialSetup()
}
func initialSetup() {
tabBar.selectedItem = tabBar.items?.first
navi = self.storyboard?.instantiateViewController(withIdentifier: "containerNavi") as? UINavigationController
firstVC = self.storyboard?.instantiateViewController(withIdentifier: "FirstViewController") as? FirstViewController
secondVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
thirdVC = self.storyboard?.instantiateViewController(withIdentifier: "ThirdViewController") as? ThirdViewController
foursVC = self.storyboard?.instantiateViewController(withIdentifier: "FoursViewController") as? FoursViewController
}
func showVC(number: Int) {
switch number {
case 0:
navi?.popToRootViewController(animated: true)
print("0")
case 1:
if let second = secondVC {
navi?.pushViewController(second, animated: true)
}
print("1")
case 2:
if let third = thirdVC {
navi?.pushViewController(third, animated: true)
}
print("2")
case 3:
if let fours = foursVC {
navi?.pushViewController(fours, animated: true)
}
print("3")
default:
return
}
}
}
extension ViewController: UITabBarDelegate {
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
showVC(number: item.tag)
}
}
您可以尝试使用此功能将4种功能之一添加/删除到ContainerView中
extension UIViewController {
func add(_ child: UIViewController, frame: CGRect? = nil) {
addChildViewController(child)
if let frame = frame {
child.view.frame = frame
}
view.addSubview(child.view)
child.didMove(toParentViewController: self)
}
func remove() {
willMove(toParentViewController: nil)
view.removeFromSuperview()
removeFromParentViewController()
}
}
//这样使用
let vc = self.storyboard?.instantiateViewController(withIdentifier: "first")
self.add(vc, frame: self.containerView.frame)
去除
vc.remove()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.