在 SwiftUI 中,如何在 XcodePreview 中设置 editMode 的环境变量 [英] In SwiftUI how do I set the environment variable of editMode in an XcodePreview
问题描述
给定这样的导航堆栈层次结构,其中将编辑按钮添加到另一个源文件中
Given a navigation stack hierarchy like this where the edit button is added in another source file
struct ContentView : View {
var body: some View {
NavigationView {
EditingView()
}.navigationBarItems(trailing: EditButton())
}
}
使用编辑按钮的视图在代码库的其他地方
And the view that uses the edit button is elsewhere in the codebase
struct EditingView : View {
@State var dataValue: String = "Initial Value"
@Environment(\.editMode) var editMode
var body: some View {
VStack(alignment: .leading) {
if self.editMode?.value == .inactive {
Text(dataValue)
} else {
TextField(($dataValue))
}
}.padding()
.navigationBarTitle("Lets edit some State")
.navigationBarItems(trailing: EditButton())
}
}
我可以在预览中以编程方式设置初始编辑模式吗?有没有办法使用环境在没有编辑按钮的情况下查看 EditingView?代码段中显示了我发现可行的几种方法,但我希望我能找到一种方法来以编程方式使用环境设置和初始值.
Can I programmatically set the initial editing mode in the preview? Is there a way to view the EditingView without an editing button using the environment? A few ways I have found that work are shown in the snippet but I would hope that I can find a method to set and initial value programmatically with the environment.
#if DEBUG
struct EditingView_Previews : PreviewProvider {
static var previews: some View {
NavigationView {
VStack {
EditingView()
// I would prefer to use an environment variable.
// Here is the best thought at some code:
//
// `.environment(\.editMode, .inactive)`
//
// the compiler Error returned:
// Type 'Binding<EditMode>?' has no member 'inactive'
//
// which I understand since it is a binding
// not a direct access to an enum variable.
// But can I set it somehow or should I let the system
// handle it entirely?
// So to get around the issue I have an extra edit button
EditButton()
}
}
}
// Or this could work
//.navigationBarItems(trailing: EditButton())
}
#endif
可以在此处找到示例项目:https://github.com/PaulWoodIII/PreviewEditMode
An Example project can be found here: https://github.com/PaulWoodIII/PreviewEditMode
推荐答案
您可以将其作为常量传入,方法是将其添加到您的预览提供程序中:
You can pass this in as a constant, by adding to your preview provider:
.environment(\.editMode, Binding.constant(EditMode.active))
例如:
struct EditingView_Previews : PreviewProvider {
static var previews: some View {
NavigationView {
EditingView()
}
}
.environment(\.editMode, Binding.constant(EditMode.active))
}
}
这篇关于在 SwiftUI 中,如何在 XcodePreview 中设置 editMode 的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!