常规高度导航栏的滚动边缘外观

Scrolling edge appearance for regular height navigation bar

我想知道是否有人知道如何让滚动边缘外观在正常高度的导航栏(不是大标题)上工作,就像在某些 Apple 自己的应用程序中一样。 在提醒应用程序中,您可以看到导航栏是清晰的,但随着 table/collection 视图向上滚动,它会动画更改导航栏以具有半透明背景。我知道我可以使用大标题获得这种行为,但在我的应用程序中,但我想模仿大标题,其中有 2 个标签垂直堆叠,就像在 Stocks 应用程序中一样。

我试过以下代码:

// default appearance with clear nav bar and no shadow
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = UIColor.clear
appearance.titleTextAttributes = [.foregroundColor: UIColor.lightText]

// scrolled appearance with the default background
// used when there's content behind the navigation view
let appearance2 = UINavigationBarAppearance()
appearance2.configureWithDefaultBackground()
//        appearance2.backgroundColor = UIColor.systemBlue
appearance2.titleTextAttributes = [.foregroundColor: UIColor.lightText]

//use clear style when there's no content behind it
navigationItem.standardAppearance = appearance

//use default style when there's content behind it
navigationItem.scrollEdgeAppearance = appearance2

当我滚动时,您可以在提醒应用中看到我的意思 Video of Reminders app scrolling navigation bar appearance behaviour

这是我的应用程序中的内容,忽略出现在导航栏中的标签,因为它在滚动时发生了变化 Video of Simulator scrolling

如果你们能帮助我,我将不胜感激

根据我的测试,该方法相当简单。请参考下面我的代码以及下面显示的结果的 gif


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tv: UITableView!

    //Custom TitleView for your navigation bar
    var titleLabel: UILabel! // 1

    override func viewDidLoad() {
        super.viewDidLoad()
        tv.delegate = self
        tv.dataSource = self

        title = nil // 2
        navigationController?.navigationBar.prefersLargeTitles = true // 2

        // Creating and setting a UILabel as the new titleView
        titleLabel = UILabel()
        titleLabel.text = "Listen Now"
        navigationItem.titleView = titleLabel // 3

        // MOST CRUCIAL
        tv.contentInset.top = -20 // 4
    }

    // MARK: UITableView delegates & datasource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.largeContentTitle = "Hello"
        return cell
    }
}
  1. 稍后您需要一个 UILabel,设置为 navigationItem.titleView
  2. 设置您的 title = nil 并确保标题是 Large title
  3. 将您的自定义标题(即我的代码中的 titleLabel)设置为 titleView
  4. 最关键的部分是将 tableView 的 contentInset.top 设置为您认为合适的值。对我来说,最佳位置是 -20(减小此值以使单元格更靠近导航栏),但您可以为其设置不同的值。 contentInset.top 相当于在 CSS 中添加 top padding,它将 tableview 顶部的间距添加到 第一个单元格 所在的位置已显示