首页 > 解决方案 > 常规高度导航栏的滚动边缘外观

问题描述

我想知道是否有人知道如何让滚动边缘外观在正常高度的导航栏(不是大标题)上工作,就像在苹果自己的一些应用程序中一样。在提醒应用程序中,您可以看到导航栏是清晰的,但随着表格/集合视图向上滚动,它会动画更改导航栏以具有半透明背景。我知道我可以使用大标题但在我的应用程序中获得这种行为,但我想模仿大标题,其中 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

当我滚动提醒应用程序滚动导航栏外观行为的视频时,您可以在提醒应用程序中看到我的意思

这是我在我的应用程序中的内容,忽略导航栏中出现的标签,因为它在 模拟器滚动的滚动视频中发生了变化

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

标签: iosswiftuikit

解决方案


根据我的测试,这种方法相当简单。请参考下面我的代码以及下面显示的结果的 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. 最关键的部分是将contentInset.top您的 tableView 设置为您认为合适的值。甜蜜点就在-20我身边(减少此值以使单元格更靠近导航栏),但您可以为其设置不同的值。contentInset.top相当于添加top paddingin CSS,它将从顶部tableview到显示第一个单元格的位置添加间距

在此处输入图像描述


推荐阅读