简体   繁体   English

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

[英]Use @EnvironmentObject with PresentationButton in SwiftUI

I am trying to pass data through an @EnvironmentObject , but it works only if I go to the next view through NavigationButton , however, I want to present the next view modally ( PresentationButton ) 我正在尝试通过@EnvironmentObject传递数据,但是仅当我通过NavigationButton转到下一个视图时,它才有效,但是,我想模态PresentationButton下一个视图( 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)")        
        }
     }
 }

What I am trying to use : 我正在尝试使用的是:

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

Try supplying the bindable object to the DetailView using environmentObject : 尝试使用environmentObject将可绑定对象提供给DetailView

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM