Search code examples
iosobjective-cxcodesafearealayoutguide

How to fix SafeAreaLayoutGuide


I am making a game with canvas. The game is clipped because of the top notch, I've tried SafeAreaLayoutGuide but nothing happened. Please look at the code below and let me know what I am doing wrong.

-(void) createGLView {
    //create our openglview and size it correctly
    OpenGLView *glView = [[OpenGLView alloc] initWithFrame:self.appDelegate.initFrame];

    self.view = glView;
    self.appDelegate.canvas = glView;

    core_init_gl(1);

    glView.backgroundColor = [UIColor redColor];
    glView.translatesAutoresizingMaskIntoConstraints = NO;

    [glView.leadingAnchor constraintEqualToAnchor:glView.safeAreaLayoutGuide.leadingAnchor].active = YES;
    [glView.trailingAnchor constraintEqualToAnchor:glView.safeAreaLayoutGuide.trailingAnchor].active = YES;
    [glView.topAnchor constraintEqualToAnchor:glView.safeAreaLayoutGuide.topAnchor].active = YES;
    [glView.bottomAnchor constraintEqualToAnchor:glView.safeAreaLayoutGuide.bottomAnchor].active = YES;

    int w = self.appDelegate.screenWidthPixels;
    int h = self.appDelegate.screenHeightPixels;
    tealeaf_canvas_resize(w, h);

    NSLOG(@"{tealeaf} Created GLView (%d, %d)", w, h);
}

The red color goes inside the top notch. I mean full screen. How to solve this?


Solution

  • You need to have a fullscreen parent view. Then you can add the OpenGLView as subview and connect its constraints to the parent view's safeAreaLayoutGuide.

    - (void)createGLView {
    
        OpenGLView *glView = [[OpenGLView alloc] initWithFrame:self.appDelegate.initFrame];
        [self.view addSubview:glView];
    
        self.appDelegate.canvas = glView;
    
        core_init_gl(1);
    
        glView.backgroundColor = [UIColor redColor];
        glView.translatesAutoresizingMaskIntoConstraints = NO;
    
        [glView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor].active = YES;
        [glView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor].active = YES;
        [glView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor].active = YES;
        [glView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor].active = YES;
    
        int w = self.appDelegate.screenWidthPixels;
        int h = self.appDelegate.screenHeightPixels;
        tealeaf_canvas_resize(w, h);
    
        NSLOG(@"{tealeaf} Created GLView (%d, %d)", w, h);
    }