繁体   English   中英

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

[英]Use @EnvironmentObject with PresentationButton in SwiftUI

我正在尝试通过@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)")        
        }
     }
 }

我正在尝试使用的是:

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

尝试使用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