Search code examples
iosobjective-ciphoneuistatusbar

iOS [Obj-C] - NavigationBar transparent with visible items while scrolling


This is my question

CONTEXT I have a ViewController which I have an effect where the Navigation Bar gets transparent when the user go down in the scroll, and the Navigation Bar gets normal when the user go up in scroll view. This effect I did with the UIScrollViewDelegate's methods. This is the code:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset = scrollView.contentOffset.y;
    if (scrollView.contentOffset.y < 0){
        scrollView.bounces = false;
    }else{
        scrollView.bounces = true;
    }
        CGFloat currentAlpha = (offset / 310);
        if (currentAlpha < 0) {
            self.navigationController.navigationBar.translucent = YES;
            self.navigationController.navigationBar.alpha = 1;
            self.navigationController.titleNavBar.alpha = 0; //This property I made in an UINavigationController extension
        } else {
            self.navigationController.navigationBar.translucent = YES;
            self.navigationController.navigationBar.alpha = 1;
            self.navigationController.titleNavBar.alpha = currentAlpha; //This property I made in an UINavigationController extension
            [self.navigationController.navigationBar setBackgroundColor:[UIColor colorWithRed:0.0f/0.0f green:136.0f/255.0 blue:206.00f/255.0f alpha:currentAlpha]];
        }
}

With the previous code I got the effect, but I have a problem: I can't add it to the status bar because self.navigationController.navigationBar.translucent is set on YES. So, in the iPhones, the status bar shows transparent and in the iPhone X shows bigger this transparence than another iPhones (see the image).

enter image description here Anyone know how can I do this transparent effect with Navigation Bar and the Statsus Bar?


Solution

  • You need to change statusBar UIView color with NavigationBar color.

    • Create AppDelegate SharedInastance :

      + (AppDelegate *)sharedAppDelegate {
      return (AppDelegate *)[UIApplication sharedApplication].delegate;
      }
      
    • Add below code in AppDelegate to get status bar view:

       - (UIView *)statusBarView {
      
          return [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
      }
      
    • Add below code when you want to change status bar color:

      [[AppDelegate sharedAppDelegate] statusBarView].backgroundColor = [UIColor redColor];
      

    enter image description here