我正在开发一个应用程序,它本质上是一系列不同的测试(为简单起见,考虑 SAT 测试或 Mensa 测试)。每个测试都在不同的 View+View Controller 中实现。
最初我想使用 Storyboards 和 UINavigationControllers 来管理测试的顺序和它们之间的转换,但现在我质疑这种方法的有效性。 UINavigationController 是一个堆栈,而我的导航只是单向的(完成测试后就无法返回)。有没有更好的方法来实现应用程序?我还能以某种方式利用 Storyboard吗?
最佳答案
我会使用自定义容器 View Controller 。所以在你的主场景中,添加一个“容器 View ”。如果您的目标是 iOS6,那么在编辑 Storyboard时,有一个特殊的“容器 View ”对象,您现在可以将其拖到自定义容器 View Controller 的场景中:
如果是 iOS 5,则 (a) 您必须手动创建第一个子场景; (b) 给它一个唯一的 Storyboard ID(在我的示例中,InitialChild
,并且 (c) 您手动实例化第一个子 Controller 并以编程方式将其添加为子 Controller 。因此,假设您有一个 UIView
在自定义容器 View Controller 的场景中调用了 containerView
,您可以使用如下方法:
- (void)addInitialChild
{
UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"InitialChild"];
[self addChildViewController:child];
child.view.frame = self.containerView.bounds;
[self.containerView addSubview:child.view];
[child didMoveToParentViewController:self];
}
当你想过渡到下一个场景时,子类化你自己的UIStoryboardSegue
:
在 ReplaceSegue.h 中:
@interface ReplaceSegue : UIStoryboardSegue
@end
在 ReplaceSegue.m 中
@implementation ReplaceSegue
- (void)perform
{
UIViewController *source = self.sourceViewController;
UIViewController *destination = self.destinationViewController;
UIViewController *container = source.parentViewController;
[container addChildViewController:destination];
destination.view.frame = source.view.frame;
[source willMoveToParentViewController:nil];
[container transitionFromViewController:source
toViewController:destination
duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
}
completion:^(BOOL finished) {
[source removeFromParentViewController];
[destination didMoveToParentViewController:container];
}];
}
@end
然后,当从第一个包含的场景到下一个场景进行转场时,指定一个“自定义”转场,并将这个“ReplaceSegue”用作类(只需单击转场以选择它,然后查看“属性”检查员”)。
生成的 Storyboard可能如下所示(注意各个子项之间的“{}
”标记):
引用资料:
有关收容的一般性讨论,请参阅 Implementing a View Container Controller在UIViewController 类引用中。
有关实现的一些细节,请参阅 Creating Custom Container View Controllers在 iOS View Controller 编程指南中。
关于iOS: "one-way"导航 Controller 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125145/