【发布时间】:2025-12-27 04:10:16
【问题描述】:
我已将 NavigationBar 添加到我的共享扩展中。添加 NavigationView 后,顶部会出现一个额外的空间(下图)。
其他答案建议删除 NavigationView.. 没有它,导航栏不会显示。
如何在保留 NavigationBar 的同时删除此空间?
class ShareViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let vc = UIHostingController(rootView: TempView())
self.addChild(vc)
self.view.addSubview(vc.view)
vc.didMove(toParent: self)
vc.view.translatesAutoresizingMaskIntoConstraints = false
vc.view.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
vc.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
vc.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
vc.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
vc.view.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
vc.view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
vc.view.backgroundColor = UIColor.clear
}
}
import SwiftUI
struct TempView : View {
var body: some View {
NavigationView {
VStack {
Text("Ok")
Spacer()
}
.navigationBarTitle("Title", displayMode: .inline)
.edgesIgnoringSafeArea(.top)
.navigationBarItems(
leading:
Text("Close"),
trailing:
Text("Next")
)
}
}
}
【问题讨论】:
-
如果你使用 SwiftUI NavigationView 你不应该通过 UIKit 设置 UINavigationBar,它们不会被合并。相反,要么只使用 NavigationView,要么尝试在显示 NavigationView 之前修改 UINavigationBar.appearance()。
-
@Asperi 感谢您的快速回复。有趣的是,如果我清除 viewWillAppear 并添加 navigationController?.navigationBar.height = true 那么 SwiftUI NavigationView 栏适当地没有空间。但是,如果我链接到另一个视图,那么很遗憾该栏不会出现。