Changing back button tint color on scroll

171 Views Asked by At

I am trying to find a way to change the tint color of the backBarButtonItem based on the scroll position. In the example below, the button should be yellow by default, but then at a certain threshold it should change to red.

Although using breakpoints I can see the code triggering in each block, but unfortunately backBarButtonItem never changes to red and always remains yellow. Any suggestions on why this might be the case? I'm assuming that you might not be able to change the back button in the navigation bar once it's already set.

    CGFloat totalHeight = CGRectGetMaxY(self.frame);
    CGFloat barHeight = CGRectGetHeight(self.frame);

    CGFloat offsetHeight = (self.scrollview.contentOffset.y - self.scrollViewMinimumOffset) + totalHeight;
    offsetHeight = MAX(offsetHeight, 0.0f);
    offsetHeight = MIN(offsetHeight, totalHeight);
    
    if (offsetHeight > barHeight * 1.0f) {
        [self.backBarButtonItem setTintColor:[UIColor redColor]];
    } else {
        [self.backBarButtonItem setTintColor:[UIColor yellowColor]];
    }
1

There are 1 best solutions below

0
Asol On

Let me provide the following example that can help you figure out or gain some ideas to better address the issue.

So in the storyboard (can be done programmatically), I have the following scenario: enter image description here

That backBarButtonItem is actually 1stVC button in the NavigationBar. In order to change the color of backBarButtonItem, you may implement the following code (or take a look):

import UIKit
class ViewController2: UIViewController {
    var counter = 0 //any conditions you want to play with

    override func viewDidLoad() {
        super.viewDidLoad()
        var color: UIColor = UIColor.purple //or yellow, by default
        if(counter == 0){
            color = UIColor.red
        }
        self.navigationController?.navigationBar.tintColor = color
    }
}

It is done in the viewDidLoad() method of ViewController2 so that it can get configured as soon as this ViewController is opened.

Here, I just used counter variable as a simple example to create some condition based on which the color of backBarButtonItem should be changed. In your case, you have another condition.

So this is the output: enter image description here