【问题标题】:How to present different navigation title when large title collapse?大标题折叠时如何呈现不同的导航标题?
【发布时间】:2019-10-26 13:29:10
【问题描述】:

目前,我在 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()

当导航栏在不再大的“正常状态”下折叠时,如何呈现完全不同的标题?

【问题讨论】:

    标签: swift uinavigationbar


    【解决方案1】:

    您可以observenavigationBarbounds 并通过检查navigationBarheight 来更改title

    1. 对于小标题height of navigationBar = 44

    2. 代表 大标题height of 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)" 是否可以使每一行颜色不同?
    • 你能看看这个帖子吗? stackoverflow.com/questions/56569515/…
    • 我发现在导航堆栈中滚动和导航时此方法存在问题。观察框架高度而不是边界高度似乎已经解决了它。
    【解决方案2】:
    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"
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2015-02-05
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多