如何防止大标题崩溃

Fre*_*eir 8 uinavigationbar uinavigationcontroller uinavigationitem ios swift

问题很简单,当滚动视图向下滚动时,如何防止大标题导航栏崩溃?

我的导航始终都必须有一个大的导航栏...因此,当滚动视图滚动时,导航栏不应合拢,它应该保持相同的大小,我该怎么做?

这就是我设置largeTitle首选项的方式

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationItem.hidesBackButton = true
    presenter.expandForSimulatorLayoutIfNeeded()

}


func expandForSimulatorLayoutIfNeeded(){
            if !isExpanded{
        topMenu = TopMenu(frame: expandedNavigationFrame, interactor: interactor)
        oldNavigationBarFrame = navigationBar.frame
        self.navigationBar.addSubview(topMenu)
    }

    if #available(iOS 11.0, *) {
        self.navigationBar.prefersLargeTitles = true
    } else {
        self.navigationBar.frame = expandedNavigationFrame
    }

    let topConstraint = NSLayoutConstraint(item: topMenu, attribute: .top, relatedBy: .equal, toItem: navigationBar, attribute: .top, multiplier: 1, constant: 0)
    let leadingConstraint = NSLayoutConstraint(item: topMenu, attribute: .leading, relatedBy: .equal, toItem: navigationBar, attribute: .leading, multiplier: 1, constant: 0)
    let widthConstraint = NSLayoutConstraint(item: topMenu, attribute: .width, relatedBy: .equal, toItem: self.navigationBar, attribute: .width, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: topMenu, attribute: .bottom, relatedBy: .equal, toItem: navigationBar, attribute: .bottom, multiplier: 1, constant: 0)
    topMenu.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([leadingConstraint, widthConstraint, topConstraint, bottomConstraint])

}
Run Code Online (Sandbox Code Playgroud)

Kam*_*ran 7

我想出的解决方法是添加一个占位符视图,该视图不是基本视图中的CollectionView/TableView第一个ViewController's视图。此第一个视图将附加到safeArea的顶部,高度可以为零。

使用情节提要/ Xib:

请参阅下面的屏幕截图,以了解此视图的约束

在此处输入图片说明

接下来,添加另一个UIView作为您的容器视图TableView/CollectionView。该容器的顶部将附加到占位符视图的底部。请参阅以下屏幕截图,以了解容器视图和TableView/CollectionView

在此处输入图片说明

此处的关键是视图层次结构中的第一个视图,因为navigation bar它将检查设置折叠效果。一旦找不到CollectionView/TableView,就不会在滚动时崩溃。

以编程方式:

如果要以编程方式设置视图的位置,则只需在顶部添加一个占位符视图。

例如,

self.view.addSubview(UIView(frame: .zero))
self.view.addSubview(tableView) // or collectionView
Run Code Online (Sandbox Code Playgroud)


Dog*_*fee 7

如果有人从 SwiftUI 来到这里,这是将列表保持在大标题模式的好方法。

// your content view ...

    var body: some View {
        VStack {
            PreventCollapseView()
            List {
                ForEach(things, id: \.self) { thing in
                    Text(thing.name)
                }
            }
        }
        .navigationBarTitle("All the things")
    }


// end of view


struct PreventCollapseView: View {

    private var mostlyClear = Color(UIColor(white: 0.0, alpha: 0.0005))

    var body: some View {
        Rectangle()
            .fill(mostlyClear)
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 1)
    }
}

Run Code Online (Sandbox Code Playgroud)