用于单个视图的 macOS SwiftUI 导航 [英] macOS SwiftUI Navigation for a Single View
问题描述
我正在尝试为我的 macOS SwiftUI 状态栏应用程序创建一个设置视图.到目前为止,我的实现一直使用 NavigationView
和 NavigationLink
,但是当设置视图将父视图推到一边时,此解决方案会产生半视图.截图和代码示例如下.
I'm attempting to create a settings view for my macOS SwiftUI status bar app. My implementation so far has been using a NavigationView
, and NavigationLink
, but this solution produces a half view as the settings view pushes the parent view to the side. Screenshot and code example below.
导航侧边栏
struct ContentView: View {
var body: some View {
VStack{
NavigationView{
NavigationLink(destination: SecondView()){
Text("Go to next view")
}}
}.frame(width: 800, height: 600, alignment: .center)}
}
struct SecondView: View {
var body: some View {
VStack{
Text("This is the second view")
}.frame(width: 800, height: 600, alignment: .center)
}
}
我能找到的少量信息表明,在 macOS 上使用 SwiftUI 是不可避免的,因为 iOS 上的全屏"NavigationView
(StackNavigationViewStyle
) 在 macOS 上不可用.
The little information I can find suggests that this is unavoidable using SwiftUI on macOS, because the 'full screen' NavigationView
on iOS (StackNavigationViewStyle
) is not available on macOS.
在 macOS 的 SwiftUI 中,是否有一种简单甚至复杂的方式来实现到设置视图的过渡?如果没有,是否可以使用 AppKit
调用 SwiftUI 编写的 View 对象?
Is there a simple or even complex way of implementing a transition to a settings view that takes up the whole frame in SwiftUI for macOS? And if not, is it possible to use AppKit
to call a View object written in SwiftUI?
也是一个 Swift 新手 - 请温柔一点.
Also a Swift newbie - please be gentle.
推荐答案
这是一个简单的演示,展示了自定义导航类解决方案的可能方法.使用 Xcode 11.4/macOS 10.15.4 测试
Here is a simple demo of possible approach for custom navigation-like solution. Tested with Xcode 11.4 / macOS 10.15.4
注意:背景颜色用于提高可见度.
struct ContentView: View {
@State private var show = false
var body: some View {
VStack{
if !show {
RootView(show: $show)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.blue)
.transition(AnyTransition.move(edge: .leading)).animation(.default)
}
if show {
NextView(show: $show)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.transition(AnyTransition.move(edge: .trailing)).animation(.default)
}
}
}
}
struct RootView: View {
@Binding var show: Bool
var body: some View {
VStack{
Button("Next") { self.show = true }
Text("This is the first view")
}
}
}
struct NextView: View {
@Binding var show: Bool
var body: some View {
VStack{
Button("Back") { self.show = false }
Text("This is the second view")
}
}
}
这篇关于用于单个视图的 macOS SwiftUI 导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!