以编程方式设置视图

时间:2016-07-08 12:16:19

标签: objective-c uiview uiviewcontroller programmatically-created

我试图设置我的项目而不使用xcode中的故事板和目标c。

我的appDelegate:

·H

#import <UIKit/UIKit.h>
#import "ViewController.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

的.m

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ViewController *vc = [[ViewController alloc] init];
    self.window.rootViewController = vc;
    return YES;
}

etc...

我的viewController文件:

的.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];

}

我认为我的代码是正确的,我运行它时应该有一个红色的屏幕,但我只得到一个黑屏。有人能告诉我,我是否忘记了某些事情,或者是否与项目设置有关。感谢。

2 个答案:

答案 0 :(得分:1)

添加

self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

application:didFinishLaunchingWithOptions:

答案 1 :(得分:0)

你错过了两个步骤。

  1. 初始化窗口:

    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    
  2. 制作窗口键&amp;可见:

    [self.window makeKeyAndVisible];
    
  3. 总而言之,您的代码应该如下所示:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        // Initialize the window
        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]; 
    
        // Add the view controller to the window
        ViewController *vc = [[ViewController alloc] init];
        self.window.rootViewController = vc;
    
        // Make window key & visible
        [self.window makeKeyAndVisible];
    
        return YES;
    }