swift - 如何在 iOS 11 上模仿 `UITableViewController` 显示 `navigationBar` 中的大标题

标签 swift uitableview ios11

我正在尝试在我的应用程序中使用 iOS 11 中的 prefersLargeTitles。它在 UITableViewController 的子类中按预期工作:

navigationController?.navigationBar.prefersLargeTitles = true

但是,在一种情况下,我需要子类化 UIViewController 并自己添加一个 TableView 。在这种情况下,我需要自己将表限制为 View :

tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.otherView.topAnchor).isActive = true

虽然这些约束呈现了 tableView 正如我所期望的那样,但现在导航栏始终使用大标题。我想模仿 UITableViewController 的行为,以便当 tableView 滚动到顶部时,会显示大标题,否则标题会折叠成普通标题。

如何解决这个问题?

最佳答案

我注意到 prefersLargeTitle 行为的另一个方面,在某些情况下可能会提供更简单、更优雅的解决方案。就我而言,viewController 不仅包含tableView(否则我会简单地使用UITableViewController,并且我会得到标准的prefersLargeTitle代码 > 开箱即用的行为),还有一些其他 View 。现在我注意到,如果将 tableView 添加为 viewController.view 的第一个 subview ,则表格将控制大标题功能:

// this will work
fileprivate func setupInitialHierarchy() {
    self.view.addSubview(tableView)
    self.view.addSubview(logoffButton)
}

在我创建 View 层次结构之前,如下所示:

// for some reason now the tableView will not control the large title
fileprivate func setupInitialHierarchy() {
    self.view.addSubview(logoffButton)
    self.view.addSubview(tableView)
}

因此,如果 tableViewviewControllerview 的第一个 subview ,我们将获得标准的大标题行为。

替代解决方案

但是,如果这是不可能的,我已经能够通过这种方式以编程方式模拟标准行为:

实现对滚动使用react的 tableView 委托(delegate)方法,然后运行使用当前 contentOffset 的代码来显示或隐藏大标题( >UITableView 继承自 UIScrollView,因此在本例中 scrollView 参数指的是 tableView):

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y <= 0 {
        self.navigationItem.largeTitleDisplayMode = .always
    } else {
        self.navigationItem.largeTitleDisplayMode = .never
    }
    self.navigationController?.navigationBar.setNeedsLayout()
    self.view.setNeedsLayout()
    UIView.animate(withDuration: 0.25, animations: {
        self.navigationController?.navigationBar.layoutIfNeeded()
        self.view.layoutIfNeeded()
    })
}

只要记住 scrollViewDidScroll 会被重复调用,因此可能需要一些guard

关于swift - 如何在 iOS 11 上模仿 `UITableViewController` 显示 `navigationBar` 中的大标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46178893/

相关文章:

ios - UINavigationController Push Segue 在 iOS11 中不起作用,没有后退按钮,没有标题

ios11 - “项目”ARFaceAnchor 指向屏幕

swift - NSTimer 在后台运行,然后恢复 (Swift)

ios - 如何将数组从 ViewController 文件发送到 Swift 文件(没有 View Controller )?

php - 快速发送http请求

json - 将嵌套的 JSON 数据列出到 TableView

swift - 如何在显示键盘时自动向上滚动表格?

swift - 当用户在单元格中键入内容时,使 UITableView 标题自动调整大小

iOS 自动布局 : Display the cell only after its contents are updated

swift - iOS Mapkit 位置 URL