我有三观。我想隐藏第三个视图中的导航栏。即使我给.navigationBarHidden(true)导航栏显示!
我找不到我做错的地方。我附上了我的代码和下面的截图。
Xcode 版本 - 11.1
struct ContentViewOne: View {
var body: some View {
NavigationView {
ZStack {
Color.yellow.edgesIgnoringSafeArea(.all)
VStack(spacing: 20) {
Text("View One")
NavigationLink(destination: ContentViewTwo()) {
Text("Navigate to View Two")
.foregroundColor(.white)
.padding()
.background(Color.red)
}
}
}
.navigationBarTitle("View One")
}
}
}
struct ContentViewTwo: View {
var body: some View {
ZStack {
Color.green.edgesIgnoringSafeArea(.all)
VStack(spacing: 20) {
Text("View Two")
NavigationLink(destination: ContentViewThree()) {
Text("Navigate to View Three")
.foregroundColor(.white)
.padding()
.background(Color.red)
}
}
}
.navigationBarTitle("View Two")
}
}
struct ContentViewThree: View {
var body: some View {
ZStack {
Color.gray.edgesIgnoringSafeArea(.all)
Text("View Three")
}
.navigationBarTitle("View Three")
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*ana 29
注意:(出于某种原因它在某些情况下有效)SwiftUI需要您需要.navigationBarTitlefor.navigationBarHidden才能正常工作。
NavigationView {
ScrollView() {
......
}.
.navigationBarTitle("") //this must be empty
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
Run Code Online (Sandbox Code Playgroud)
我尝试了多种解决方案,包括 UINavigationControllerDelegate,但似乎没有什么可以使导航栏永久隐藏。直到我尝试了 KVO :)
因此,如果您想要永久解决方案,请使用以下命令:
struct NoBarNavigationView<Content: View>: View {
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
NavigationView {
content
.introspectNavigationController { (UINavigationController) in
NavigationControllerDelegate.shared.becomeDelegate(of: UINavigationController)
}
}
}
}
class NavigationControllerDelegate: NSObject {
static let shared = NavigationControllerDelegate()
func becomeDelegate(of navigationController: UINavigationController) {
navigationController.isNavigationBarHidden = true
navigationController.navigationBar.isHidden = true
navigationController.navigationBar.addObserver(self, forKeyPath: "alpha", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// This is necessary to ensure the UINavigationBar remains hidden
if let navigationBar = object as? UINavigationBar {
navigationBar.isHidden = true
}
}
}
Run Code Online (Sandbox Code Playgroud)
快乐编码!
编辑:正如评论中指出的,我正在使用:
import Introspect
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9818 次 |
| 最近记录: |