如何预览依赖于PresentationMode的SwiftUI按钮?

4
如何预览需要PresentationMode才能构建的此按钮? 在包含该按钮的主视图中,通过声明一个环境PresentationMode对象来创建它,该按钮可以正常工作:
@Environment(\.presentationMode) var presentationMode:Binding<PresentationMode>

struct BackButton: View {
  @Binding var presentationMode: PresentationMode
  var color: Color
  var body: some View {
    Button(action: {
      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 {
        let pres = PresentationMode()
      return BackButton(presentationMode: pres, color: .black) // Compiler Error: PresentationMode cannot be constructed because it has no accessible initializers
    }
}
1个回答

1
我认为PresentationMode应该被声明为环境变量。 所以像这样声明它。
@Environment(\.presentationMode) var presentationMode

然后在操作中进行更改,因为它不再是绑定。

Button(action: {
    self.presentationMode.wrappedValue.dismiss()

编辑:

这里有一个可工作的示例/预览,展示了BackButton View和如何使用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)
    }
}

这是在正常代码中的工作方式。但我的问题是关于预览。在预览中,我无法创建按钮。 - onthemoon
@onthemoon 但你仍然可以使用BackButton(color: .black)执行预览,为什么需要在预览中使用演示模式? - davidev
我明白了。你的意思是必须将绑定传递给presentationMode,因为它可以在BackButton结构体内声明为环境变量。太好了!谢谢。 - onthemoon
是的,我建议并经常阅读将其声明为环境。因此,在创建视图时无需使用绑定,预览将与环境一起工作。 - davidev
1
我完全同意。 - onthemoon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接