SwiftUI 视图构建器参数无法更改状态。

3

我正在尝试创建一个SwiftUI视图,其中可以传递一个视图构建器。但是使用视图构建器参数时,我无法更改状态。这是由于在init方法中创建的原因吗? 如何实现我期望的行为?

struct Card_Previews: PreviewProvider {
    
    @State
    static var bol: Bool = true
    static var previews: some View {
        Label(title: { content })
    }
    
    // Does not change the value
    private static var content: some View {
        Button(bol.description) {
            bol.toggle()
        }
    }
}


struct Label<Title>: View where Title: View {

    var body: some View {
        title
    }

    let title: Title
    public init(@ViewBuilder title: () -> Title) {
        self.title = title()
    }
}

如果有什么不明白的地方,请问一下:

1个回答

1

您的问题与@ViewBuilder无关,原因是bol是一个State而不是Binding。要解决此问题,您需要将这两个属性绑定在一起,例如:

struct Label<Title>: View where Title: View {

    @Binding
    var bol: Bool
    
    var body: some View {
        HStack {
            title
            Button(bol.description) {
                // Changes the value
                bol.toggle()
                print(bol.description)
            }
        }
    }
    
    let title: Title
        
    
    public init(bol: Binding<Bool>, @ViewBuilder title: () -> Title) {
        self.title = title()
        self._bol = bol
    }
}

Card_Previews中,将Label(title: { content })替换为Label(Bol: $bol, title: { content })


这好像也不起作用。:( - Tbi
为什么在预览中bol是静态的? - Timmy
是的,那就是问题所在。非常感谢你。我只是太专注于@State了,忽略了static。 - Tbi
我不知道我们现在该如何获得一个被接受的答案,或者我是否应该将其删除。 - Tbi
1
这是你的决定! - Timmy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接