我试图理解为什么当我将带有 SwiftUI View 的 UIHostingViewController 推送到我的导航堆栈时,当导航标题出现时会有轻微的延迟,正如您从这个演示中看到的那样:
代码:
struct SwiftUIView: View {
var body: some View {
EmptyView()
.navigationTitle("SwiftUI View")
}
}
与使用标题立即可见的 UIViewController 相比:
我能想到的解决方案之一是在将
.title
推入堆栈之前添加 UIHostingViewController
,但我想知道是否有办法从 SwiftUI 组件修复它?
这是说明我所描述内容的项目:https://github.com/ignotusverum/NavigationTitlesTesting
完整代码:
class ViewController: UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let button = UIButton(type: .system)
button.addTarget(self,
action: #selector(buttonTapped),
for: .touchUpInside)
button.setTitle("Push SwiftUI View", for: .normal)
let button2 = UIButton(type: .system)
button2.addTarget(self,
action: #selector(button2Tapped),
for: .touchUpInside)
button2.setTitle("Push UIViewController", for: .normal)
let stackView = UIStackView(arrangedSubviews: [button, button2])
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.heightAnchor.constraint(equalToConstant: 120),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
self.view = view
}
@objc func buttonTapped() {
let hostingController = UIHostingController(rootView: SwiftUIView())
navigationController?.pushViewController(hostingController,
animated: true)
}
@objc func button2Tapped() {
let viewController = UIViewController()
viewController.view.backgroundColor = .white
viewController.title = "UIViewController"
navigationController?.pushViewController(viewController,
animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Navigation Test"
navigationItem.backButtonTitle = "Back"
}
}
struct SwiftUIView: View {
var body: some View {
EmptyView()
.navigationTitle("SwiftUI View")
}
}
附:
出现这个问题似乎是因为大标题异步更新了它的外观。当 UIHostingController 从 SwiftUI 视图的环境中读取导航标题时会发生延迟。