【发布时间】:2019-07-07 15:06:56
【问题描述】:
给定这样的导航堆栈层次结构,其中编辑按钮被添加到另一个源文件中
struct ContentView : View {
var body: some View {
NavigationView {
EditingView()
}.navigationBarItems(trailing: EditButton())
}
}
使用编辑按钮的视图在代码库的其他地方
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?我发现工作的几种方法显示在 sn-p 中,但我希望我能找到一种方法来通过环境以编程方式设置和初始值。
#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
【问题讨论】:
-
作为记录,
Binding可以使用.constant(value)代替实际值初始化为常量。所以.environment(\.editMode, .constant(.inactive))可以设置环境变量。