当我使用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")
}
}