我正在尝试设置一个 UIScrollView,以便我可以在我的 3 个 View Controller 之间滑动。这是我在 AppDelegate.m 中的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.;
UIScrollView *sv = [[UIScrollView alloc] init];
BarsViewController *bvc = [[BarsViewController alloc] init]; // Create BarsViewController
StopwatchViewController *svc = [[StopwatchViewController alloc] init]; // Create StopwatchViewController
TimerViewController *tvc = [[TimerViewController alloc] init]; // Create TimerViewController
[sv addSubview:bvc.view];
[sv addSubview:svc.view];
[sv addSubview:tvc.view];
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade]; // Hide status bar
self.window.rootViewController = sv;
[self.window makeKeyAndVisible];
return YES;
}
它在这一行给出错误:
self.window.rootViewController = sv;
说,“从 UIScrollView *' 分配给 'UIViewController *' 的不兼容指针类型”。
但是,没有 UIScrollViewController 这样的东西,所以我不知道该怎么做。
基本上,我只想让整个屏幕成为一个 ScrollView ,这样我就可以在我的 3 个 View Controller 之间滑动。我该怎么做?
最佳答案
UPD:2015 年 6 月 swift
概念保持不变,这在下面的 Objective-C 部分中进行了描述。语法上有一点变化。要添加 childviewcontroller,请使用以下代码段:
let aViewController = storyboard.instantiateViewControllerWithIdentifier("A") as! AViewController;
addChildViewController(aViewController);
scrollView!.addSubview(aViewController.view)
aViewController.didMoveToParentViewController(self)
objective-C
创建您自己的自定义容器 View Controller (我将其称为 combinedViewController),它将在 ScrollView 中保存您的三个 Controller 。
像往常一样继承 UIViewController,然后在新的 combinedViewController -viewDidLoad:
中使用 addChildViewController 公共(public) API,如下所示:
[self addChildViewController:aViewController];
[self.scrollView addSubview:aViewController.view];
[aViewController didMoveToParentViewController:self];
代码的作用如下:
- 它调用容器的 addChildViewController: 方法来添加 child 。
- 它访问 subview 的属性以检索 View 并将其添加到自己的 View 层次结构中。容器在添加 View 之前设置 child 的大小和位置;容器始终选择 child 的内容出现的位置。
- 它显式调用 child 的 didMoveToParentViewController: 方法来表示操作已完成。
对每个 viewController 执行此操作。之后,将您的 combinedViewController 设置为 rootViewController。
如果您需要进一步的解释,请随时询问。
引用:Design custom container view controller
这是我的Objective-C Github sample code
UPD:感谢@Oliver Atkinson 澄清 addChildViewController:
方法还会自动调用 child 的 willMoveToParentViewController:
方法。
结果:
关于ios - 设置 UIScrollView 以在 3 个 View Controller 之间滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19820939/