SwiftUI 在预览模式下使用按钮关闭模态
SwiftUI close modal with a button in preview mode
我有一个简单的 Button,当它被点击时会打开一个 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
}
}
我有一个简单的 Button,当它被点击时会打开一个 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
}
}