更喜欢带有 GroupedListStyle SwiftUI 视图的 LargeTitles

prefersLargeTitles with a GroupedListStyle SwiftUI view

我有一个 parent 视图,我希望其中的导航标题较大。然后我推送一个 child 视图和一个分组的 table 视图,我想导航标题是 inline:

这适用于 SwiftUI,但是当我的 parent 是带有 prefersLargeTitles = true 的 UIViewController 并且我在 child 跳转中推送 UIHostingController(rootView: ChildView()) 导航栏标题时

这是预期的行为(仅使用 SwiftUI)

这是从 UIKit 推送时的行为:

这是有效的 SwiftUI 代码

struct ParentView: View {
    var body: some View {
        NavigationView {
            Text("SwiftUI")
                .navigationBarItems(trailing: navigationButton)
                .navigationBarTitle("SwiftUI Parent", displayMode: .large)
        }
    }

    var navigationButton: some View {
        NavigationLink(destination: ChildView()) {
            Text("Push")
        }
    }
}

struct ChildView: View {
    let list = ["One", "Two", "Three"]
    var body: some View {
        List(list, id: \.self, rowContent: Text.init)
            .listStyle(GroupedListStyle())
            .navigationBarTitle("SwiftUI Child", displayMode: .inline)
    }
}

struct ChildView_Previews: PreviewProvider {
    static var previews: some View {
        ChildView()
    }
}

这就是我从 UIKit

推送 SwiftUI child 的方式
class ParentViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "UIKit Parent"

        let barItem = UIBarButtonItem(title: "Push", style: .plain, target: self, action: #selector(pushChild))
        navigationItem.rightBarButtonItem = barItem
        view.backgroundColor = UIColor.systemBackground
        navigationController?.navigationBar.prefersLargeTitles = true
    }

    @objc
    func pushChild(_ sender: Any) {
        let childViewController = UIHostingController(rootView: ChildView())
        navigationController?.pushViewController(childViewController, animated: true)

    }
}

在推送之前将子视图控制器的 navigationItem.largeTitleDisplayMode 设置为 .never(即使它是 UIHostingController)。

func pushChild(_ sender: Any) {
    let childViewController = UIHostingController(rootView: ChildView())
    childViewController.navigationItem.largeTitleDisplayMode = .never
    navigationController?.pushViewController(childViewController, animated: true)
}