我现在有3个视图控制器:一个MenuViewController
和两个顶级视图控制器,名为HomeViewController
和FoodCraftsViewController。每个顶级控制器都在故事板中的自己的导航控制器中,因为它们最终将具有子视图控制器。 MenuViewController在故事板中是独立的。我以编程方式将MenuViewController
作为子视图添加到这些顶级视图控制器,以便以导航栏动画显示视图的方式显示菜单,主视图动画显示仅显示顶部部分内容。
我已将MenuViewController
作为单例类,因为所有顶级视图控制器都将使用它。我在Xcode中看到的是,当你在菜单中更改视图时,内存会慢慢增加,这让我相信它每次都会创建一个新的导航控制器。
MenuViewController
代码:
class var sharedInstance: MenuViewController {
struct Static {
static var instance: MenuViewController?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MenuViewController") as? MenuViewController
}
return Static.instance!
}
用于在顶级视图之间导航的MenuViewController代码(这是我怀疑代码不必要地创建导航控制器的地方):
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
if self.parentViewController! != homeVC {
if homeVC == nil {
homeVC = storyboardMain.instantiateViewControllerWithIdentifier("HomeViewController") as? HomeViewController
}
navController = UINavigationController(rootViewController: homeVC!)
navController!.navigationBar.translucent = false
navController!.extendedLayoutIncludesOpaqueBars = true
self.presentViewController(navController!, animated: false, completion: nil)
} else {
homeVC?.hideMenu()
}
} else if indexPath.row == 1 {
if self.parentViewController! != foodCraftsVC {
if foodCraftsVC == nil {
foodCraftsVC = storyboardMain.instantiateViewControllerWithIdentifier("FoodCraftsViewController") as? FoodCraftsViewController
}
navController = UINavigationController(rootViewController: foodCraftsVC!)
navController!.navigationBar.translucent = false
navController!.extendedLayoutIncludesOpaqueBars = true
self.presentViewController(navController!, animated: false, completion: nil)
} else {
foodCraftsVC?.hideMenu()
}
}
}
在顶级视图控制器(HomeViewController和FoodCraftsViewController)中使用的代码添加菜单:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(false);
for view in menuView.subviews {
view.removeFromSuperview()
}
menuVC = MenuViewController.sharedInstance
addChildViewController(menuVC!)
menuView.addSubview(menuVC!.view)
menuVC!.didMoveToParentViewController(self)
menuVC!.homeVC = self
}
对优化此代码表示赞赏。谢谢!