簡體   English   中英

UIViewController子視圖存在,但我看到黑屏

[英]UIViewController subviews exist but I see black screen

我有2個視圖控制器,第一個是情節提要(這是根),第二個是無節制。 當我按下根視圖控制器中的按鈕時,它應該調用第二個控制器。

這是我的第二個視圖控制器的代碼:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UILabel *sampleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0,0,100,100)];
        UIImageView * basketItem = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"B.jpg"]];
        [self.view addSubview:sampleLabel];
        [self.view addSubview:basketItem];
        NSLog(@"%@",self.view.subviews);
        sampleLabel.text = @"Main Menu";
    }
    return self;
}

self.view.sebviews查詢顯示存在2個對象label和imageView對象,但實際上我只看到黑屏。

這是過渡方法

- (void)transitionToViewController:(UIViewController *)aViewController
  withOptions:(UIViewAnimationOptions)options
{
      aViewController.view.frame = self.containerView.bounds;
      [UIView transitionWithView:self.containerView
                  duration:0.65f
                   options:options
                animations:^{
                    [self.viewController.view removeFromSuperview];
                    [self.containerView addSubview:aViewController.view];
                }
                completion:^(BOOL finished){
                    self.viewController = aViewController;
                }];    
}

將代碼viewDidLoad 在這里,您確定視圖已加載到內存中,因此可以進一步自定義。

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILabel *sampleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0,100,100,100)];
    UIImageView * basketItem = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"B.jpg"]];
    [self.view addSubview:sampleLabel];
    [self.view addSubview:basketItem];
    NSLog(@"%@",self.view.subviews);
    sampleLabel.text = @"Main Menu";    
}

如果不使用ARC,請注意內存泄漏。

注意

我真的建議閱讀Apple文檔。 您應該了解事情的運作方式。 希望能有所幫助。

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html

編輯

我不知道可能是什么問題。 要使其工作,請嘗試重寫loadView (在MenuViewController )方法,如下所示:

- (void)loadView
{
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
    contentView.backgroundColor = [UIColor redColor]; // red color only for debug purposes
    self.view = contentView;
}

保留我寫的viewDidLoad方法,看看會發生什么。

創建視圖控制器時,只能使用init方法。

MenuViewController *vc = [[MenuViewController alloc] init];

您的UILabelframesize.width=0

CGRectMake(0,100,0,100)

如果未將B.jpg添加到項目中,則UIImageView也將為空。

另外,如果第二個UIViewController沒有XIB,請使用- (id)init方法而不是- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

暫無
暫無

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

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