我正在尝试在我的应用程序中使用 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)
}
因此,如果 tableView
是 viewController
的 view
的第一个 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/