您可以在 Swift/SwiftUI 中的自定义结构初始值设定项中访问 @Environment 值吗?
我一直在尝试根据 this 实现自定义后退按钮发布。似乎关于如何关闭 NavigationLink 的最常见响应是通过通过以下方式访问@Environment值presentationMode:
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
然后在自定义按钮结构中调用dismiss方法:
var btnBack : some View { Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image("ic_back") // set image here
.aspectRatio(contentMode: .fit)
.foregroundColor(.white)
Text("Go back")
}
}
}
是否可以在结构中的自定义初始值设定项中访问presentationMode var?我尝试过类似的操作:
init(var: Variable) {
self.presentationMode = @Environment(\.presentationMode)
self.var = var
}
或:
var presentationMode: Binding<PresentationMode>
init(var: Variable) {
presentationMode = @Environment(\.presentationMode)
self.var = var
}
或(根据 Apple Docs):
init(var: Variable) {
@Environment(\.dismiss) var dismiss
self.var = var
}
上面似乎初始化了,但在范围内找不到解雇。 iOS/Swift 新手不确定这是否可行,但感谢任何指导!
I've been trying to implement a custom back button according to this posting. Seems as though most common response in how to dismiss a NavigationLink is through accessing the @Environment value presentationMode through:
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
And then calling dismiss Method in a custom button struct:
var btnBack : some View { Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image("ic_back") // set image here
.aspectRatio(contentMode: .fit)
.foregroundColor(.white)
Text("Go back")
}
}
}
Is it possible to access the presentationMode var in a custom initializer in a struct? I've tried things like:
init(var: Variable) {
self.presentationMode = @Environment(\.presentationMode)
self.var = var
}
or:
var presentationMode: Binding<PresentationMode>
init(var: Variable) {
presentationMode = @Environment(\.presentationMode)
self.var = var
}
or (with dismiss action per Apple Docs):
init(var: Variable) {
@Environment(\.dismiss) var dismiss
self.var = var
}
The above seems to initialize, but can't find dismiss in scope. New to iOS/Swift & not sure this is possible, but appreciate any guidance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案是否定的,您无法访问初始化程序中的环境,但这不是必需的。您可以访问环境值,而无需将它们分配给您的视图结构。
The answer is no, you can't access the environment in the initializer, but that's not necessary. You can access the environment values without assigning them to your View struct.