gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:16:27 25 4
gpt4 key购买 nike

我正在尝试在我的应用程序中使用来自 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 behavior out-of-the-box),还有一些其他的 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 ,我们就会得到标准的大标题行为。

替代方案

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

为响应滚动的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com