Paul Paul - 5 months ago 12
Objective-C Question

Setting the view programmatically

I am trying to set my project without using storyboards in xcode and with objective c.

My 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...


My viewController file:

.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];

}


I think my code is right and we should have a red screen when I run it, but I only get a black screen. Can someone tell me if I have forgotten something or is it something to do with the project settings. Thanks.

Answer

You are missing two steps.

  1. Initialize the window:

    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    
  2. Make the window key & visible:

    [self.window makeKeyAndVisible];
    

So all together, your code should look like this:

- (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;
}