Home > OS >  How to use scrollEdgeAppearance in iOS 15?
How to use scrollEdgeAppearance in iOS 15?

Time:03-19

Here's Apple's document of scrollEdgeAppearance for UINavigationBar:

When a navigation controller contains a navigation bar and a scroll view, part of the scroll view’s content appears underneath the navigation bar. If the edge of the scrolled content reaches that bar, UIKit applies the appearance settings in this property.

If the value of this property is nil, UIKit uses the settings found in the standardAppearance property, modified to use a transparent background. If no navigation controller manages your navigation bar, UIKit ignores this property and uses the standard appearance of the navigation bar.

When running on apps that use iOS 14 or earlier, this property applies to navigation bars with large titles. In iOS 15, this property applies to all navigation bars.

Here's my demo. I embed ViewController into a UINavigationController, then drag a UITableView and set it as the subview of ViewController's view. I set the following appearance properties to UINavigationBar:

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let redAppearance = UINavigationBarAppearance()
        redAppearance.backgroundColor = .red
        navigationController?.navigationBar.standardAppearance = redAppearance
        
        let greenAppearance = UINavigationBarAppearance()
        greenAppearance.backgroundColor = .green
        navigationController?.navigationBar.scrollEdgeAppearance = greenAppearance
    }
}

I thought the initial navigation bar should be red, and it should turn green when I scroll the table view. But the truth is it's the other way around.

Initial State Scrolling State

I did some search and most people just set standardAppearance and scrollEdgeAppearance to the same instance, or set one of them to be nil, so I'm quite confused about these two properties in iOS 15.

CodePudding user response:

You have understood perfectly but backward.

navigationController?.navigationBar.scrollEdgeAppearance = greenAppearance

means the nav bar will be green only when the scrollable view is scrolled all the way down. That is what you see in your first screen shot.

As soon as you scroll up a little bit, the nav bar starts adopting its standard appearance, which is red. That is what you see in your second screen shot.

CodePudding user response:

scrollEdgeAppearance is applied when the edge of the scrollable content reaches the nav bar so what you're seeing is correct. Many people set both scrollEdgeAppearance and standardAppearance to the same since they want the behavior to be no different when the user scrolls but your implementation is certainly a valid use case.

  • Related