Nesting GLKView into UIViewController

JohnnyAce picture JohnnyAce · Mar 18, 2012 · Viewed 8.8k times · Source

I'm trying to use GLKView in UIViewController, my code looks like this

CustomViewController.h

#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>

@interface CustomViewController : UIViewController
{
    NSString * name;
}

@property NSString * name;

CustomViewController.m

#import "CustomViewController.h"

@interface CustomViewController ()

@end

@implementation CustomViewController
@synthesize name;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    EAGLContext * context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    CGRect mainScreen = [[UIScreen mainScreen] bounds];
    GLKView * viewGL = [[GLKView alloc] initWithFrame:CGRectMake(mainScreen.size.width / 2, mainScreen.size.height / 2, 50, 50)];
    viewGL.context = context;
    [self.view addSubview:viewGL];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

How can I define the draw/render method of GLKView? and where can I init OpenGL? Any suggestions?

Answer

Scott Hyndman picture Scott Hyndman · Mar 18, 2012

Initialize OpenGL in your viewDidLoad, just as you're currently doing.

Take a look at registering your view controller as the GLKView's delegate. The delegate's glkView:(GLKView *)view drawInRect: method will be invoked whenever a redraw is required.

This tutorial may help.