我在UIViewController的导航栏中以编程方式创建了一个UISegmentedControl,我希望能够在切换分段控件时切换视图控制器。
这是我到目前为止所做的:
@interface TVExploreViewController : TVViewController
@property (nonatomic, strong) UISegmentedControl *scopeControl;
@property (nonatomic, assign) NSInteger scope;
@property (nonatomic, strong) UIViewController *premiumContentViewController;
@property (nonatomic, strong) UIViewController *trendingContentViewController;
@property (nonatomic, strong) UIViewController *currentViewController;
@end
TVExploreViewController的实现:
- (void)viewDidLoad {
[super viewDidLoad];
_scopeControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"TV & MOVIES", @"VIRAL CLIPS", nil]];
[_scopeControl setFrame:CGRectMake(80, 0, 200, 30)];
[_scopeControl addTarget:self
action:@selector(scopeChanged:)
forControlEvents:UIControlEventValueChanged];
[[self navigationItem] setTitleView:_scopeControl];
[_scopeControl setSelectedSegmentIndex:0];
_premiumContentViewController = [[TVPremiumContentViewController alloc] init];
_trendingContentViewController = [[TVTrendingFeedController alloc] init];
[self setScope:0];
}
- (void)scopeChanged:(id)sender {
[self setScope:self.scopeControl.selectedSegmentIndex];
}
- (void)transitionToViewController:(UIViewController *)controller
{
[self.currentViewController willMoveToParentViewController:nil];
if (controller) {
[self addChildViewController:controller];
}
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
[self.currentViewController.view removeFromSuperview];
[self.currentViewController removeFromParentViewController];
[controller didMoveToParentViewController:self];
self.currentViewController = controller;
}
- (void)setScope:(NSInteger)scope {
if (scope != _scope) {
_scope = scope;
UIViewController *nextController = nil;
if (_scope == 0) {
nextController = self.premiumContentViewController;
} else if (_scope == 1) {
nextController = self.trendingContentViewController;
}
[self transitionToViewController:nextController];
}
}
当我在TVExploreViewController中切换分段控件时,视图的其余部分保持白色并且没有加载视图控制器。谁知道我做错了什么?
答案 0 :(得分:0)
这不是答案,但在这里写一些日志代码很方便。
你能告诉我方法中的日志吗?
- (void)transitionToViewController:(UIViewController *)controller
{
[self.currentViewController willMoveToParentViewController:nil];
if (controller) {
[self addChildViewController:controller];
}
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
[self.currentViewController.view removeFromSuperview];
[self.currentViewController removeFromParentViewController];
[controller didMoveToParentViewController:self];
self.currentViewController = controller;
// can you show me the log here ?
NSLog(@"%@, %@, %@", controller.view, controller.view.superview, self.view) ;
// you should see the subviews that you added.
NSLog(@"subviews:%@", [controller.view subviews]) ;
}
答案 1 :(得分:0)
将Viewcontrollers添加到ViewController真的不是一个好主意,你应该总是在屏幕上有一个ViewController。您可以使用NavigationController执行此操作,而无需动画。