在SwiftUI中将@EnvironmentObject与PresentationButton一起使用

时间:2019-06-14 07:54:35

标签: ios swift swiftui

我正在尝试通过@EnvironmentObject传递数据,但是只有当我通过NavigationButton进入下一个视图时,该方法才有效,但是,我想模态呈现下一个视图({{1} })

PresentationButton

我要使用的内容:

struct ContentView : View {

     @EnvironmentObject var settings: UserSettings

     var body: some View {
        NavigationView {
        VStack {
            // A button that writes to the environment settings
            Button(action: {
                self.settings.score += 1
            }) {
                Text("Increase Score")
            }
            NavigationButton(destination: DetailView()) {
                Text("Show Detail View")
            }
        }
      }
   }
}

struct DetailView: View {
     @EnvironmentObject var settings: UserSettings

     var body: some View {
     // A text view that reads from the environment settings
        VStack {
            Text("Score: \(settings.score)")        
        }
     }
 }

1 个答案:

答案 0 :(得分:1)

尝试使用DetailView将可绑定对象提供给environmentObject

PresentationButton(Text("Show Detail View"), 
                   destination: DetailView().environmentObject(settings))