本文介绍了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<Bool>类型的参数:

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初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:35