当我使用 UIHostingController 将新的 SwiftUI.View 推送到现有 UIKit UIViewController 的导航堆栈时,导航栏中的标题动画被破坏。我在 Xcode 12.0 中对一个纯新项目进行了测试。
仔细观察标题“UIHostingController”。您可以看到动画看起来与普通推送动画有何不同,它只是“出现”无中生有,看起来很破碎。第二个动画已经从 SwiftUI.NavigationLink 发生,看起来不错。
如果您想尝试一下,这里是示例项目的链接: https ://www.dropbox.com/s/mjkuzhpsb6yvlir/HostingControllerTest.zip?dl=0
查看此 GIF 图片:(如果您没有查看 GIF 动画,请在另一个浏览器选项卡中打开)
这是后面的代码:
class ViewController: UIViewController {
private let button = UIButton(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UIHostingController Title Test"
self.view.backgroundColor = UIColor.white
self.view.addSubview(self.button)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Push UIHostingController", for: .normal)
button.addTarget(self, action: #selector(Self.pushVC), for: .touchUpInside)
button.setTitleColor(.blue, for: .normal)
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
button.widthAnchor.constraint(equalTo: self.view.widthAnchor),
button.heightAnchor.constraint(equalToConstant: 50)
])
}
@objc private func pushVC() {
let vc = UIHostingController(rootView: Content())
self.navigationController?.pushViewController(vc, animated: true)
}
}
struct Content: View {
var body: some View {
NavigationLink(destination: Content2()) {
Text("Push NavigationLink")
}
.navigationTitle("UIHostingController")
}
}
struct Content2: View {
var body: some View {
Text("Coming from NavigationLink")
.navigationTitle("Native SwiftUI View")
}
}