Switch between UIViewControllers using UISegmentedControl

馋奶兔 提交于 2020-01-10 04:34:27

问题


I have a tabbar -> navigationcontroller structure. In one of these tabs, I want to switch between two UIViewControllers (a KalViewController and a UITableViewController to be be exact), using a UISegmentedControl located in the Navigation Bar.

Currently, I have a third UIViewController, that pops and pushes the appropriate ViewControllers on segment value change. I don't think thats the right way to do it and it also destroys the navigation stack (when I tap on the bar item, the navigation controller goes the root controller, which won't work). And there's even another bug, related to the Kal Component.

So, what's the right way to do it?


回答1:


The right way to do it is to have the controller handling the UISegmentedControl add the views of the controllers as subviews.

[self.view addSubview:controller.view];

It's your responsibility to send viewWillAppear: and so on.

EDIT: The offset you're talking about can be adjusted using:

controller.view.frame = CGRectMake(x, y, width, height);

EDIT 2: In response to tc.'s comment:

From the documentation of UISplitViewController:

Message Forwarding to Its Child View Controllers

A split view controller interposes itself between the application’s window and its child view controllers. As a result, all messages to the visible view controllers must flow through the split view controller. This works generally as you might expect and the flow of messages should be relatively intuitive. For example, view appearance and disappearance messages are sent only when the corresponding child view controller actually appears on screen. Thus, when a split view controller is first displayed in a portrait orientation, it calls the viewWillAppear: and viewDidAppear: methods of only the view controller that is shown initially. The view controller that is presented using a popover does not receive those messages until the popover is shown or until the split view controller rotates to a landscape orientation.

This is not magical and there is no reason why you wouldn't be able to write a similar controller yourself. In fact I've done it and it worked just fine.



来源:https://stackoverflow.com/questions/5555218/switch-between-uiviewcontrollers-using-uisegmentedcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!