2016-07-22 74 views
0

我想添加一個子視圖按鈕單擊。但是當點擊按鈕時,視圖不會出現。iOS addSubview不顯示視圖

下面是點擊按鈕的很乾脆代碼:

-(IBAction) dimChangeBtnClick: (id) sender 
{ 
    [self addSubview:myHelloWorldViewController.view]; 
} 

myHelloWorldViewController是HelloWorldViewController類的一個實例。

HelloWorldViewController.h:

#import <UIKit/UIKit.h> 

@interface HelloWorldViewController : UIViewController 

-(IBAction)showMessage; 

@end 

和HelloWorldViewController.m:

#import <Foundation/Foundation.h> 
#import "HelloWorldViewController.h" 

@implementation HelloWorldViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 


    if (self) { 
     // Custom initialization 

    } 
    return self; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

-(IBAction)showMessage 
{ 
    UIAlertView *hellowWorldAlert = [[UIAlertView alloc] initWithTitle:@"My First App" message:@"Hello, World!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    [hellowWorldAlert show]; 
} 

@end 

我想表明的觀點是 HelloWorldViewController.xib

是否有在objective-之間需要一些額外的鏈接c代碼和.xib文件,除了命名它們相同嗎?從我的大二問題可以明顯看出,我對iOS很新,所以任何建議都將不勝感激。請告訴我是否有任何我遺漏的關鍵信息。

回答

1

如果您想要將來自另一個UIViewController的視圖嵌入到您的主視圖控制器中,則需要一點過程來正確地將該視圖的某些控件轉移到主視圖控制器。這在詳細these Apple docs

如果你喜歡一個更教程式的演練描述,那麼你就可以try this one

+0

謝謝!這些資源非常有用,絕對有我需要的信息。 –

0

你有沒有初始化myHelloWorldViewController?

myHelloWorldViewController = [[HelloWorldViewController alloc] init]; 
0

這條線是有問題的:

[self addSubview:myHelloWorldViewController.view]; 

首先,你指的是一個名爲myHelloWorldViewController變量。但它是什麼,它是如何獲得其價值的?你沒有表現出來,所以沒有理由認爲它甚至是的HelloWorldViewController。

二,你在做什麼是錯的。您不能僅僅通過創建視圖控制器來實現垃圾箱 - 潛入nib文件並拉出視圖。你可以自由地從一個筆尖加載視圖,但不是這樣。至於在你的視圖中放置另一個視圖控制器的視圖,有關於如何做到這一點的非常嚴格的規則(你必須將其他視圖控制器正式配置爲視圖控制器的子視圖),並且你沒有遵循這些規則。

0

在這裏,您正在使用另一個ViewController,所以你必須先初始化它,然後你必須呈現它。

SampleViewController *new = [[SampleViewController alloc]initWithNibNam:@"SampleViewController" bundle:nil]; 
[self presentViewController:new animated:Yes completion:nil]; 

如果您在同一個ViewController中使用簡單的視圖,您可以簡單地使用addsubView函數將它添加到當前視圖中。