SwiftUI NavigationView显示不正确

时间:2020-10-19 02:25:04

标签: swift swiftui swiftui-navigationview

我正在学习SwiftUI,并遵循Apple的“地标”教程,然后通过示例进行尝试,并尝试使用这些知识来制作自己的东西。

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

Apples代码:

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

它产生了这个:

enter image description here

我的代码:

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")
    }
}

它产生了这个:

enter image description here

这是在iPhone 11模拟器上。

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

>

1 个答案:

答案 0 :(得分: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")
        }
    }
}

demo