SwiftUI:如何在单击按钮时显示视图? [英] SwiftUI: How to present view when clicking on a button?

查看:390
本文介绍了SwiftUI:如何在单击按钮时显示视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Apple的 SwiftUI 制作应用,并且我需要有两个按钮,它们可以在单个List行中显示两个不同的视图.

I'm trying to make an app using Apple's SwiftUI and I need to have two buttons that present two different views in a single List row.

我使用 Xcode beta 7 MacOS Catalina beta 7 .我尝试添加表示视图的Button,但是我无法单击它,而当我尝试在List外部的简单Button并单击它时,没有出现AddList()视图.我也尝试在navigationButton内添加navigationButton,但是它也没有用.单击tapAction也不起作用,该视图仍然不会出现

I use Xcode beta 7 and MacOS Catalina beta 7. I've tried to add a Button that present the view but, I couldn't click it and when I tried on a simple Button outside the List and clicked it, the AddList() view didn't appear. I've also tried adding a navigationButton inside navigationButton but it didn't work too. Adding a tapAction doesn't work too when you click on it, the view still does not appear

NavigationView {
            List(0..<5) { item in
                NavigationLink(destination: ContentOfList()) {
                    Text("hello") // dummy text
                    Spacer()
                    Text("edit")
                        .tapAction {
                            AddList() // This is the view I want to present
                    }
                }
                }.navigationBarItems(trailing: NavigationLink(destination: AddList(), label: { // doesn't work within navigationBarItems
                    Image(systemName: "plus.circle.fill")
                }))
        }

我希望出现AddList()视图,但在两种情况下不会出现.

I expect the AddList() view to appear but in the two cases, it doesn't.

推荐答案

改进的版本(SwiftUI,iOS 13 beta 7)

Much improved version (SwiftUI, iOS 13 beta 7)

相同的解决方案适用于消除.sheet修饰符提供的模态.

The same solution works for dismissing Modals presented with the .sheet modifier.

import SwiftUI

struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: { self.presentationMode.wrappedValue.dismiss() }
        )
    }
}

struct RootView: View {
    var body: some View {
        VStack {
            NavigationLink(destination: DetailView())
            { Text("I am Root. Tap for Detail View.") }
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            RootView()
        }
    }
}

这篇关于SwiftUI:如何在单击按钮时显示视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆