gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:14:49 36 4
gpt4 key购买 nike

如何预览需要 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
}
}

最佳答案

我认为 PresentationMode 应该声明为环境变量。

所以这样声明..

@Environment(\.presentationMode) var presentationMode

然后像那样改变它,因为它不再是绑定(bind)了。

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)
}
}

关于swiftui - 如何预览依赖于 PresentationMode 的 SwiftUI 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62702068/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com