当大标题折叠时如何呈现不同的导航标题?

6

目前,我已经在ViewController的viewDidLoad方法中使用以下代码启用了导航栏的大标题:

navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationItem.largeTitleDisplayMode = .automatic
        
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd"
let result = formatter.string(from: date)

self.title = "This is a Test\n\(result)"

var count = 0
for item in(self.navigationController?.navigationBar.subviews)! {
    for sub in item.subviews {
        if sub is UILabel {
            if count == 1 {
                break;
            }
            let titleLab :UILabel = sub as! UILabel
            titleLab.numberOfLines = 0
            titleLab.text = self.title
            titleLab.lineBreakMode = .byWordWrapping
            count = count + 1
        }
    }
}
self.navigationController?.navigationBar.layoutSubviews()
self.navigationController?.navigationBar.layoutIfNeeded()

当导航栏折叠并不再占据大面积时,我该如何呈现完全不同的标题?

2个回答

12

您可以通过检查 navigationBar 的高度来观察边界并更改标题

1. 对于小标题navigationBar高度= 44

2. 对于大标题navigationBar高度> 44

class VC: UIViewController {
    var observer: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.observer = self.navigationController?.navigationBar.observe(\.bounds, options: [.new], changeHandler: { (navigationBar, changes) in
            if let height = changes.newValue?.height {
                if height > 44.0 {
                    //Large Title
                    self.title = "Large Title"
                } else {
                    //Small Title
                    self.title = "Small Title"
                }
            }
        })
    }
}

输入图像描述


快速的侧面问题,如果您注意到我的原始代码将标题分成两行:self.title = “This is a Test\n\(result)"。是否可以使每一行都有不同的颜色? - user11349745
你能否请看一下这篇帖子?https://stackoverflow.com/questions/56569515/change-the-color-of-text-in-this-custom-navigation-bar-with-two-rows - user11349745
1
我发现在导航堆栈中滚动和导航时,这种方法存在问题。观察框架高度而不是边界高度似乎已经解决了这个问题。 - Drew
我可以确认观察边界存在问题,它显示的是45、46、47而不是44。使用.frame则正常。 - ChikabuZ
有没有人了解 SwiftUI 中的等效内容? :) - Nicolai Harbo

3
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let heightForCollapsedNav = UINavigationController().navigationBar.frame.size.height
    let navHeight = navigationController!.navigationBar.frame.size.height
    navigationController?.navigationBar.topItem?.title = navHeight <= heightForCollapsedNav  ? "Collapsed" : "Large"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接