2012-04-25 70 views
0

我試着在單個視圖內顯示多個UIViewController對象。目前我想在應用程序加載時顯示單個UIViewController對象。但是應用程序屏幕顯示爲空白,而應該在子視圖控制器內顯示一個標籤。iOS:UIViewController不顯示使用故事板的另一個UIViewController

這裏是我做過什麼:

ParentViewController.h

#import <UIKit/UIKit.h> 
@interface ParentViewController : UIViewController 
{ 
    UIViewController *child1Controller; 
    UIViewController *child2Controller; 
} 
@end 

ParentViewController.m

#import "ParentViewController.h" 
#import "Child1Controller.h" 
#import "Child2Controller.h" 

@interface ParentViewController() 
@end 

@implementation ParentViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { ... } 

- (void)viewDidLoad 
{ 
    child2Controller = [[Child2Controller alloc] init]; 
    [self.view addSubview:child2Controller.view]; 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 

} 

- (void)viewDidUnload { ... } 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { ... } 

@end 

然後在Interface Builder故事板

  • 添加3視圖控制器
  • 爲其中的每一個分配了一個類ParentViewController,Child1Controller & Child2Controller
  • 在Child2Controller對象中,在View中添加了一個UILabel。在Child2Controller.h
  • 定義的IBOutlet中進行的UILabel和Child2Controller.m
  • 增加了合成語句相同
  • 最後在項目的Info.plist設置的主要故事板文件

難道我在想念的東西這裏?

回答

3

從iOS 5開始,可以利用View Controller Containment。這是一種新的方法,允許您創建自定義控制器容器,如UINavigationControllerUITabBarController

就你而言,這可能非常有用。事實上,在故事板中,您可以創建父控制器和兩個子控制器。父母可以鏈接到另一個場景,而兩個孩子沒有鏈接。它們是獨立的場景,您可以在您的父控制器中使用它們。

例如,在父控制器的viewDidLoad方法,你可以做到以下幾點:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIStoryboard *storyboard = [self storyboard]; 

    FirstChildController *firstChildScene = [storyboard instantiateViewControllerWithIdentifier:@"FirstChildScene"]; 
    [self addChildViewController:firstChildScene]; 
    [firstChildScene didMoveToParentViewController:self]; 
} 

然後在你的FirstChildController覆蓋didMoveToParentViewController

- (void)didMoveToParentViewController:(UIViewController *)parent 
{ 
    // Add the view to the parent view and position it if you want 
    [[parent view] addSubview:[self view]]; 
    CGRect newFrame = CGRectMake(0, 0, 350, 400); 
    [[self view] setFrame:newFrame]; 
} 

,瞧!您有一個包含由子控制器管理的一個視圖的控制器。請參閱how-does-view-controller-containment-work-in-ios-5

希望它有幫助。

+0

+1這確實工作得很好。但是我想知道的是我在問題中發佈的代碼/流程中所做的錯誤。 – vikmalhotra 2012-04-26 02:21:57

+0

@ShiVik那麼Child2Controller呢?它是用xib加載還是覆蓋* loadView *方法? – 2012-04-26 07:46:44

+0

不,我沒有創建一個新的xib文件,也沒有'loadView'。我所做的是我在故事板中添加了一個UIViewController,並在身份檢查器中將其自定義類分配爲「Child2Controller」。 – vikmalhotra 2012-04-26 08:12:16

相關問題