Using GLKView with a UIViewController

2020-07-26 13:53发布

问题:

I wanted to use OpenGL to do some simple Image processing, so I started off with GLKView. Since I don't need to refresh the view every few seconds, I didn't use the GLKViewController and instead used a normal UIViewController subclass.

My question is that do I simply make the viewController's view as a GLKView or do I add the GLKView as a subview of the view controller's view. Since I'm adding a UISlider to the view as well, I think the latter seems better, but I'm not sure. I also need to call setNeedsDisplay on the GLKView on certain occasions.

回答1:

For your rendering, you should really be using GLKView inside a GLKViewController. if you're worried about not needing to refresh all the time, use self.paused = YES inside your GLKViewController, this will stop the rendering loop, and when you need to render again, simply do self.paused = NO.

if you're having the glkview inside another view, you should set it up with containment. in your case, you should have a normal UIView with a normal UIViewController, then add the UISlider and your GLKViewController (with the GLKView) to that.

After this is done, you can do your normal view stuff in your parent controller, and your opengl stuff is your glk controller.

A simple example to do this, having setup your parent, which contains the UISlider:

inside the custom UIViewController for the parent

@interface ParentViewController () {
    ...
    UISlider *_slider; // this is your slider
    CustomGLKViewController *_myGlkViewController;
}

then inside viewDidLoad:

// assuming you're using a storyboard
UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                      bundle:[NSBundle mainBundle]];


// setup the opengl controller
// first get an instance from storyboard
_myGlkViewController = [myStoryboard instantiateViewControllerWithIdentifier:@"idForGlkViewController"];
// then add the glkview as the subview of the parent view
[self.view addSubview:_myGlkViewController.view];
// add the glkViewController as the child of self
[self addChildViewController:_myGlkViewController];
[_myGlkViewController didMoveToParentViewController:self];

// if you want to set the glkView to the same size as the parent view, 
// or you can do stuff like this inside myGlkViewController
_myGlkViewController.view.frame = self.view.bounds;

but this is just a simple example to help you get started, you should really go read the apple docs on UIViewController containment for ios5 and the docs for GLKit