SwiftUI @Binding 初始化 [英] SwiftUI @Binding Initialize

查看:53
本文介绍了SwiftUI @Binding 初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止一直在玩 SwiftUI 并理解 BindableObjects 等的概念(至少我希望我这样做).

Been playing around with SwiftUI and understood the concept of BindableObjects etc so far (at least I hope I do).

我遇到了一个似乎找不到答案的愚蠢问题:如何初始化 @Binding 变量?

I bumped into a stupid problem I can't seem to find an answer for: How do you initialize a @Binding variable?

我有以下代码:

struct LoggedInView : View {

    @Binding var dismissView: Bool

    var body: some View {
        VStack {
            Text("Hello World")
        }
    }
}

在我的预览代码中,我想传递 Binding 类型的参数:

In my preview code, I want to pass that parameter of type Binding<Bool>:

#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
    static var previews: some View {
        LoggedInView(dismissView: **Binding<Bool>**)
    }
}
#endif

我将如何初始化它?试过了:

How would I go an initialize it? tried:

Binding<Bool>.init(false)
Binding<Bool>(false)

甚至:

@Binding var dismissView: Bool = false

但没有一个成功......有什么想法吗?

But none worked... any ideas?

推荐答案

当您在应用中使用 LoggedInView 时,您确实需要提供一些绑定,例如 @State 来自上一个视图或 @EnvironmentObject.

When you use your LoggedInView in your app you do need to provide some binding, such as an @State from a previous view or an @EnvironmentObject.

对于 PreviewProvider 的特殊情况,您只需要一个固定值,您可以使用 .constant(false)

For the special case of the PreviewProvider where you just need a fixed value you can use .constant(false)

例如

#if DEBUG
struct LoggedInView_Previews : PreviewProvider {
    static var previews: some View {
        LoggedInView(dismissView: .constant(false))
    }
}
#endif

这篇关于SwiftUI @Binding 初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆