SwiftUI-导航栏未显示在模态NavigationView中

时间:2019-11-07 20:50:23

标签: ios swift swiftui

尝试创建类似于Apple日历应用程序中的“创建事件”模态的模态。我已经在父级NavigationView中使用以下代码成功显示了模态:

.navigationBarItems(trailing:
                    Button(action: {
                        self.isModal = true
                        }) {
                        Image(systemName: "plus").sheet(isPresented: $isModal, content: {
                            EventCreate(showModal: self.$isModal)
                        })
                    }
            )

模式显示成功,但是我无法在模式中显示NavigationBar,如下所示:

struct EventCreate: View {

    @Binding var showModal: Bool

    @State var event = Event(id: 0, title: "", description: "", location: "", start: Date(), end: Date(), cancelled: false, public_occurrence: false, created: "", last_updated: "", guests: -1)

    var body: some View {
        NavigationView {
            Form{
                Section {
                    TextField("Title", text: $event.title)
                    TextField("Location", text: $event.location)
                }
                Section {
                    DatePicker(selection: $event.start, label: { Text("Start") })
                    DatePicker(selection: $event.end, label: { Text("End") })
                }
            }
        }
        .navigationBarTitle(Text("Create Event"), displayMode: .inline)
        .navigationBarItems(leading:
            Button("Close") {
                self.showModal = false
        })

    }
}

将构建应用程序,并显示“表单”,但NavigationView不会: Screenshot of missing view

我该如何演出?还是我应该使用另一个视图代替NavigationView

1 个答案:

答案 0 :(得分:2)

您需要将navigationBarTitlenavigationBarItems修饰符放在NavigationView内,而不是外面。这些修饰符必须放在要嵌入的视图上,以Form

为例
struct EventCreate: View {

    @Binding var showModal: Bool

    @State var event = Event(id: 0, title: "", description: "", location: "", start: Date(), end: Date(), cancelled: false, public_occurrence: false, created: "", last_updated: "", guests: -1)

    var body: some View {
        NavigationView {
            Form{
                Section {
                    TextField("Title", text: $event.title)
                    TextField("Location", text: $event.location)
                }
                Section {
                    DatePicker(selection: $event.start, label: { Text("Start") })
                    DatePicker(selection: $event.end, label: { Text("End") })
                }
            }
            .navigationBarTitle(Text("Create Event"), displayMode: .inline)
            .navigationBarItems(leading:
            Button("Close") {
                self.showModal = false
            })
       }
    }
}

HackingWithSwift的此article显示正确的位置。