You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UITableView滚动时固定导航栏与大标题(Swift实现)

解决UITableView滚动时导航栏与大标题固定的问题

要让导航栏和大标题在UITableView滚动时保持静态,不随滚动收缩或隐藏,只需在导航栏配置代码中添加关键设置,并修正TableView的布局约束,具体步骤如下:

1. 调整导航栏核心设置

在configNavBar()方法中补充以下代码,强制大标题始终显示并禁用导航栏滑动隐藏:

func configNavBar() {
    navigationController?.navigationBar.barTintColor = .black
    navigationController?.navigationBar.backgroundColor = .black
    self.title = "Bitcoin"
 
    let navBarAppearance = UINavigationBarAppearance()
    navBarAppearance.shadowColor = .clear
    navBarAppearance.shadowImage = UIImage()
    navBarAppearance.backgroundColor = .black
    navBarAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    
    navigationController?.navigationBar.standardAppearance = navBarAppearance
    navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance

    // 启用大标题模式
    navigationController?.navigationBar.prefersLargeTitles = true
    // 设置大标题始终显示,不随滚动切换为普通标题
    navigationItem.largeTitleDisplayMode = .always
    // 禁用导航栏随滑动隐藏的特性,确保导航栏一直固定显示
    navigationController?.hidesBarsOnSwipe = false

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Log out", style: .done, target: self, action: #selector(didTapLogout))
    self.navigationItem.rightBarButtonItem?.tintColor = .systemGray  
}

2. 修正TableView布局约束

现有代码未给TableView添加自动布局约束,可能导致滚动时布局异常。在setupTableView()方法中添加约束,让TableView贴紧安全区域:

func setupTableView() {
    view.addSubview(tableView)
    tableView.separatorColor = .label
    tableView.layer.shadowColor = UIColor.black.cgColor
    tableView.layer.shadowOffset = CGSize(width: 0, height: 0)
    tableView.backgroundColor = .systemBackground
    tableView.tableFooterView = UIView()
    tableView.isScrollEnabled = true
    tableView.showsVerticalScrollIndicator = true
    tableView.clipsToBounds = true
    let nib = UINib(nibName: "ChatTableViewCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "ChatTableViewCell")
    
    // 关闭自动转换约束,添加布局约束
    tableView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])
}

关键设置说明

  • navigationController?.navigationBar.prefersLargeTitles = true:开启导航栏的大标题模式
  • navigationItem.largeTitleDisplayMode = .always:指定当前页面的大标题始终保持显示状态,不会在滚动时收缩为普通标题
  • navigationController?.hidesBarsOnSwipe = false:确保导航栏不会随TableView的滑动操作自动隐藏
  • TableView约束绑定到safeAreaLayoutGuide:避免TableView内容被导航栏遮挡,同时确保滚动行为不会影响导航栏的位置

内容的提问来源于stack exchange,提问作者husharoonie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:13:16