【问题标题】:SWIFTUI Button or NavigationLink?SWIFTUI 按钮或 NavigationLink?
【发布时间】:2021-03-26 05:39:01
【问题描述】:

我有一个名为“保存”的按钮,用于保存用户输入。 但是,我想让它像,如果用户点击按钮“保存”,那么屏幕会自动返回到上一个视图。我可以通过向 Button 中的操作添加代码来做到这一点吗?还是我必须使用 NavigationLink 而不是 Button?

 Button(action: {
                let title = shortcutTitle
                currentShortcutTitle = title
                UserDefaults.standard.set(title, forKey: "title")
            }, label: {
                Text("Save")
                    .padding()
                    .frame(width: 120, height: 80)
                    .border(Color.black)
            }) //: Button - save

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    如果您只是想返回上一个视图并且已经在NavigationView 堆栈中,您可以使用@Environment(\.presentationMode)

    struct ContentView: View {
        
        var body: some View {
            NavigationView {
                NavigationLink(destination: Screen2()) {
                    Text("Go to screen 2")
                }
            }.navigationViewStyle(StackNavigationViewStyle())
        }
    }
    
    struct Screen2 : View {
        @Environment(\.presentationMode) var presentationMode  //<-- Here
    
        var body: some View {
            Button("Dismiss") {
                presentationMode.wrappedValue.dismiss() //<-- Here
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 2020-12-29
      • 2020-07-25
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2019-12-25
      相关资源
      最近更新 更多