1

我正在学习 SwiftUI 并遵循 Apple 的“Landmark”教程,然后举一些例子,并尝试利用这些知识制作我自己的例子。

但是,我真的缺少一些理解,因为我不明白为什么我会出现非标准行为。

苹果代码:

struct CategoryHome: View
{
    var body: some View
    {
        NavigationView
        {
            Text("Landmarks Content")
                .navigationBarTitle(Text("Featured"))
        }
    }
}

它产生了这个:

在此处输入图像描述

我的代码:

struct ContentView: View
{
    @State private var selection: String? = nil
    
    var body: some View
    {
        NavigationView
        {
            NavigationLink(destination: Text("Second View"), tag: "Second", selection: $selection) { EmptyView() }
            NavigationLink(destination: Text("Third View"),  tag: "Third",  selection: $selection) { EmptyView() }
            NavigationLink(destination: Text("Forth View"),  tag: "Forth",  selection: $selection) { EmptyView() }
        
            VStack
            {
                Text("Content View")
                Spacer()
                Button("Press to goto 2nd view", action: { self.selection = "Second" })
                Button("Press to goto 3rd view", action: { self.selection = "Third" })
                Button("Press to goto 4th view", action: { self.selection = "Forth" })
                Spacer()
            }
        }
        .navigationBarTitle("Home")
    }
}

它产生了这个:

在此处输入图像描述

这是在 iPhone 11 模拟器上。

有人可以简单地解释一下,为什么这些如此不同以及为什么我没有得到我想要的结果(这是一个带有标题的主“屏幕”,3 个按钮,在 iPhone 上纵向显示时。

4

1 回答 1

3

NavigationView期望在一个视图中(不是大量视图),所以下面是可能的解决方案(使用 Xcode 12 / iOS 14 测试):

struct ContentView: View
{
    @State private var selection: String? = nil
    
    var body: some View
    {
        NavigationView
        {
            VStack
            {
                Text("Content View")
                Spacer()
                Button("Press to goto 2nd view", action: { self.selection = "Second" })
                Button("Press to goto 3rd view", action: { self.selection = "Third" })
                Button("Press to goto 4th view", action: { self.selection = "Forth" })
                Spacer()
            }
            .background(Group {
                    NavigationLink(destination: Text("Second View"), tag: "Second", selection: $selection) { EmptyView() }
                    NavigationLink(destination: Text("Third View"),  tag: "Third",  selection: $selection) { EmptyView() }
                    NavigationLink(destination: Text("Forth View"),  tag: "Forth",  selection: $selection) { EmptyView() }
            })
                .navigationBarTitle("Home")
        }
    }
}

演示

于 2020-10-19T04:02:35.250 回答