Cannot set custom class to GLKView inside UIView

2019-08-02 01:32发布

问题:

I am learning OpenGL ES for iOS and following Ray Wenderlich's tutorial online. The first thing he does is set the view in a view controller to a different color using OpenGL ES 2.0. So I created the custom class called OpenGLView which is responsible for changing the color of the screen. Then in the main story board I deleted the original view in the view controller and replaced it with a GLKView and set its class to OpenGLView. When I run the project everything works fine. But now I was trying to do the same, except the GLKView is inside a UIView. Like the following

When I set the class of the GL View to my custom class OpenGlView in the main storyboard it does not except the class. And when I run the project all I see is a white screen.

How can I set the GL View to the OpenGLView class?

Edit:

I believe it has something do with the code in the app delegate.

@interface AppDelegate : UIResponder <UIApplicationDelegate>{

OpenGLView* _glView;
}
 @property (strong, nonatomic) UIWindow *window;
 @property (nonatomic, retain) IBOutlet OpenGLView *glView;

 @end

//In the implementation
@synthesize glView=_glView;

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    self.glView = [[OpenGLView alloc] initWithFrame:screenBounds];
    [self.window addSubview:_glView];
    return YES;
}

回答1:

Your code creates a glView in the app delegate as adds it as subview of the root window; afterwards a view controller is instantiated through the storyboard and its view added to the stack. This last view is the white view you see and it covers the glView. To better understand such hierarchy you can use the Xcode Debug View Hierarchy functionality. To solve your issue you can either remove the view controller or move your glView as subview of the view controller.

EDIT: If you create the OpenGLView through a storyboard, initWithCoder is used and not initWithFrame. Add the following method to OpenGLView.m:

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self) {
        [self setupLayer];
        [self setupContext];
        [self setupRenderBuffer];
        [self setupFrameBuffer];
        [self render];
    }
    return self;
}