在预览模式下使用按钮关闭SwiftUI模式



我有一个简单的按钮,当它被点击时,它会打开一个模态。我知道模态可以通过向下滑动来关闭,但我实现了一个按钮来关闭它,这很有效。

唯一困扰我的是,我无法预览我的Modal(看看下面的代码(


// Button that opens the modal
struct ContentView: View {
@State private var willMoveToNextScreen = false
Button(action: {
self.willMoveToNextScreen = true
}, label: {
Image(systemName: "gear")
.font(.system(size: 30))
.padding(.leading, 15)
})
.sheet(isPresented: $willMoveToNextScreen, content: {
SettingsView(willMoveToNextScreen: $willMoveToNextScreen)
})
}

// Modal
struct SettingsView: View {
@Binding var willMoveToNextScreen: Bool

var body: some View {
VStack{
HStack {
Button(action: {
self.willMoveToNextScreen = false
}, label: {
Image(systemName: "xmark")
.font(.system(size: 30, weight: .semibold))
})
}
.frame(maxWidth: .infinity, alignment: .trailing)
.padding(15)
Spacer()
Text("Aye")
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
// I don't know which value I should provide, it expects a Binding<Bool> value
SettingsView(willMoveToNextScreen: ??) 
}
}

willMoveToNextScreen需要BindingBoolean。我该怎么解决这个问题?

使用Binding.constant(true)。您可以使用Binding.constant(/*Pass your default value as per type*/)PreviewProvider设置数据。

struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView(willMoveToNextScreen: .constant(true)) // Pass true or false
}
}

最新更新