Search code examples
iosuinavigationbarios11

iOS 11 Large Title change event


I want to get the event when iOS 11 large title changes. i.e. When it changes the place to & from navigation bar when user scrolls the view. I've checked the UINavigationBar class but nothing I can get it from.

The screen design I want to implement is like when Large title is visible I want transparent Navigation bar but when title scrolled up to navigation bar I want nav bar with solid colour.


Solution

  • I have added this observer in my UIViewController's subclass's ViewWillAppear. and setting the color according to its height as below:

    In ViewWillAppear:

    UINavigationBar *navBar = self.navigationController.navigationBar;
    [navBar addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
    

    In viewWillDisappear:

    UINavigationBar *navBar = self.navigationController.navigationBar;
    [navBar removeObserver:self forKeyPath:@"frame" context:NULL];
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"frame"]) {
        [self setNavigationBarColour];;
    }
    

    }

    - (void)setNavigationBarColour
    {
        UINavigationBar *navBar = self.navigationController.navigationBar;
        CGFloat height = navBar.bounds.size.height;
        if(height>44)
        {
            [navBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
            [navBar setTranslucent:YES];
            [navBar setShadowImage:[UIImage new]];
        }
        else
        {
            [navBar setBackgroundImage:[[UINavigationBar appearance] backgroundImageForBarMetrics:UIBarMetricsDefault] forBarMetrics:UIBarMetricsDefault];
            [navBar setTranslucent:NO];
            [navBar setShadowImage:[[UINavigationBar appearance] shadowImage]];
        }
    }