如何预览依赖于PresentationMode的SwiftUI按钮?
我如何预览这个需要PresentationMode才能构建的按钮? 该按钮在包含它的主视图中运行良好。它使用声明为以下内容的environment PresentationMode对象创建该按钮:如何预览依赖于PresentationMode的SwiftUI按钮?,swiftui,Swiftui,我如何预览这个需要PresentationMode才能构建的按钮? 该按钮在包含它的主视图中运行良好。它使用声明为以下内容的environment PresentationMode对象创建该按钮: @Environment(\.presentationMode) var presentationMode:Binding<PresentationMode> 我认为PresentationMode应该声明为环境变量 那么就这样宣布吧 @Environment(\.presentatio
@Environment(\.presentationMode) var presentationMode:Binding<PresentationMode>
我认为PresentationMode应该声明为环境变量 那么就这样宣布吧
@Environment(\.presentationMode) var presentationMode
然后像这样改变它,因为它不再是一个绑定
Button(action: {
self.presentationMode.wrappedValue.dismiss()
编辑:
下面是BackButton视图的预览示例/以及如何使用PresentationMode
struct MainView: View {
var body: some View {
NavigationView
{
VStack()
{
Text("Hello World")
NavigationLink("Go to Detail View", destination: BackButton(color: .black))
}.navigationBarTitle(Text("Main View"))
}
}
}
struct BackButton : View
{
//Environment variable here
@Environment(\.presentationMode) var presentationMode
var color: Color
var body: some View
{
Button(action: {
//Dismiss the View
self.presentationMode.wrappedValue.dismiss()
}, label: { Image(systemName: "chevron.left")
.scaleEffect(1.3)
.foregroundColor(color)
.offset(x: -17)
.frame(width: 43, height: 43)
})
}
}
struct BackButton_Previews: PreviewProvider {
static var previews: some View {
//Preview here is working, no need to pass environment variable
//Going back from this view in Preview won't work
BackButton(color: .black)
}
}
这就是它在普通代码中的工作方式。但我的问题是关于预演。在预览中,我无法创建button@onthemoon但是,您仍然可以使用BackButton(颜色:。黑色)执行预览。为什么在预览中需要该演示模式?我现在就知道了。您基本上是说将绑定传递到presentationMode是必要的,因为它可以在BackButton结构中声明为环境。伟大的谢谢。。我建议/并且经常读到您将其声明为环境。因此,无需使用绑定,在创建视图时必须设置绑定。预览将与环境一起工作我完全同意
struct MainView: View {
var body: some View {
NavigationView
{
VStack()
{
Text("Hello World")
NavigationLink("Go to Detail View", destination: BackButton(color: .black))
}.navigationBarTitle(Text("Main View"))
}
}
}
struct BackButton : View
{
//Environment variable here
@Environment(\.presentationMode) var presentationMode
var color: Color
var body: some View
{
Button(action: {
//Dismiss the View
self.presentationMode.wrappedValue.dismiss()
}, label: { Image(systemName: "chevron.left")
.scaleEffect(1.3)
.foregroundColor(color)
.offset(x: -17)
.frame(width: 43, height: 43)
})
}
}
struct BackButton_Previews: PreviewProvider {
static var previews: some View {
//Preview here is working, no need to pass environment variable
//Going back from this view in Preview won't work
BackButton(color: .black)
}
}