簡體   English   中英

iOS:UIViewController不會使用故事板顯示另一個UIViewController

[英]iOS: UIViewController doesn't display another UIViewController using storyboards

我正在嘗試在單個視圖中顯示多個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

然后在界面構建器的情節提要中

  • 添加3個視圖控制器
  • 為他們每個人分配一個類ParentViewController,Child1Controller和Child2Controller
  • 在Child2Controller對象中,在View內部添加了UILabel。
  • 在Child2Controller.h中,為UILabel定義了IBOutlet,並在Child2Controller.m中為其添加了synthesize語句
  • 最后在project-Info.plist中設置主故事板文件

我在這里錯過了什么嗎?

從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];
}

和瞧! 您有一個控制器,其中包含一個由子控制器管理的視圖。

有關更多信息,請參見ios-5中的view-viewes-controller-containment-work-in-ios-5

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM