Swift 4:使用UIView作为框架呈现ViewControllers

时间:2018-05-30 14:12:39

标签: ios swift uiview viewcontroller

我会尽力解释我的问题,所以提前谢谢。

我通常通过让每个ViewController代表不同的视图来构建具有许多视图控制器的应用程序。现在,我正在创建一个包含许多不同视图的大型应用程序。我不希望在我的应用程序中有15个以上的View Controllers。我宁愿让一个ViewController继承不同的UIViews。

例如,如果在我的菜单栏上选择"设置"选项。然后我将被带到selectionController并让selectionController继承名为Settings View的UIView

目前我可以导航到我的settingsController并让Navbar代表所选的选项。但是我如何继续继承View?

选择某个选项时,会调用此功能..

//Whatever option selected will affect which view is inherited

    let option = self.menuOptions[indexPath.row]
        if option.name != "Home" {
            self.homeController?.displayController(menuOption: menuOption, view: self.settingsView)
        }

家庭控制器

class HomeController: UIViewController {
lazy var menu: Menu = {
    let menuLauncher = Menu()
    menuLauncher.homeController = self
    return menuLauncher
}()

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Home"
        view.backgroundColor = Color.blue
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "menu"), style: .plain, target: self, action: #selector(displayMenu))
}

func displayController(menuOption: MenuOption, view: UIView) {
    let selectionController = UIViewController()
    selectionController.navigationItem.title = menuOption.name
    selectionController.view.backgroundColor = Color.blue

//Why dosen't this present the view I have assigned to it??
    selectionController.view.addSubview(HomeView(frame: view.frame))
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.pushViewController(selectionController, animated: true)
}

@objc func displayMenu() {
    menu.displayMenu()
}

}

1 个答案:

答案 0 :(得分:1)

您似乎正在此处的“设置”视图中发送:

self.homeController?.displayController(menuOption: menuOption, view: self.settingsView)

但我不知道您将该视图实际分配给视图控制器的位置:

func displayController(menuOption: MenuOption, view: UIView) {
    //[...]
    //What is HomeView?  
    selectionController.view.addSubview(HomeView(frame: view.frame))
    //[...]
    navigationController?.pushViewController(selectionController, animated: true)
}

您将HomeView传递给ViewController,而不是传入视图,并将HomeView的大小设置为传入视图的框架(在本例中为“设置”)。

我希望这样的事情:

func displayController(menuOption: MenuOption, view: UIView) {
   let selectionController = UIViewController()
   selectionController.navigationItem.title = menuOption.name
   selectionController.view.backgroundColor = Color.blue

   selectionController.view.addSubview(view)

   navigationController?.navigationBar.tintColor = UIColor.white
   navigationController?.pushViewController(selectionController, animated: true)
}

不知道HomeView的功能,但假设它有其他你想要的东西,也许传入的视图会成为HomeView的子视图,那么HomeView会返回你想要的东西。在那种情况下:

 selectionController.view.addSubview(HomeView(selectedView: view))

在这种情况下,HomeView应该从传入视图内部推断出它的帧大小,因此不需要frame参数。