ViewController以编程方式?

时间:2012-10-24 12:04:04

标签: ios xcode uiview uiviewcontroller

我想知道在xcode中创建一个新的“单视图”项目后需要执行哪些步骤,以实现: 1.一个viewController,它在没有NIB的情况下进行初始化,而是以编程方式在其视图中加载它自己的控件 2.如何将viewcontroller的视图转到load并调用viewDidLoad
3.使用所有控件在屏幕上显示该控制器的视图。

我如何从这个功能中解决这个问题:

-(BOOL)application:(UIApplication*)application didFinishLoadingWithOptions:(NSDictionary *)launchOptions 

我正在尝试修改一个新的xcode项目,但我得到的只是一个黑色的屏幕,viewDidLoad没有被调用

4 个答案:

答案 0 :(得分:1)

UIViewController *myViewController = [[UIViewController alloc] init];
[myViewController.view setFrame:self.view.bounds];
[self.view addSubview:myViewController.view]; // if you want to add it in another viewcontroller

// For testing, set the background color to something other than white (default)

[myViewController.view setBackgroundColor:[UIColor greenColor]];

然后你走了!

答案 1 :(得分:1)

这是你的app delegate的应用程序加载方法。

在那里,你可能想要创建一个自定义视图控制器的实例,并将其作为rootViewController分配给你的app delegate didFinishLoading。应该有一句话:

// app delegate .h file

#import "CustomViewController.h"

@interface
{
    ...
    CustomViewController *myCustomVC;
    ...
}

@property (nonatomic, retain) CustomViewController *myCustomVC;


// app delegate .m file
@implementation AppDelegate

@synthesize myCustomVC;

-(BOOL)application:(UIApplication*)application didFinishLoadingWithOptions:(NSDictionary *)launchOptions 
{
    ...
    myCustomerVC = [[CustomViewController alloc] init];

    [self.window setRootViewController:myCustomVC]; 
    ...
}

然后在自定义视图控制器的viewDidLoad方法中,您可以将其作为测试:

// custom view controller .m file
-(void)viewDidLoad
{
    self.view.backgroundColor = [UIColor redColor];
}

答案 2 :(得分:1)

您需要创建UIViewController的子类,并在loadViewviewDidLoad中设置视图层次结构(取决于自定义级别)

通过继承UIViewController,您将获得加载方法调用,因此您无需担心获取viewDidLoad等。

要使其在屏幕上可见,最简单的方法是将其设置为应用窗口的rootViewController

在您的app delegate中的didFinishLaunchingWithOptions:

self.window.rootViewController = [[MyViewControllerSubclass alloc] init];

答案 3 :(得分:0)

试试这个:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    HomeViewController *homeVC = [[HomeViewController alloc]init];
    [self.window setRootViewController:homeVC];
    [self.window makeKeyAndVisible];
    return YES;
}

从常规设置的主界面中删除Main(故事板参考): enter image description here

添加启动图片: 并在左下角设置中选择iOS-7及更高版本 enter image description here