SwiftUI @Binding更新不会刷新视图 [英] SwiftUI @Binding update doesn't refresh view

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

问题描述

我觉得我缺少一些非常基本的东西,但是此示例SwiftUI代码在单击按钮时不会修改视图(尽管进行了绑定更新)

I feel like I'm missing something very basic, but this example SwiftUI code will not modify the view (despite the Binding updating) when the button is clicked

教程我阅读过,建议这是使用绑定的正确方法,视图应自动刷新

Tutorials I have read suggest this is the correct way to use a binding and the view should refresh automatically

import SwiftUI

struct ContentView: View {
    @Binding var isSelected: Bool

    var body: some View {
        Button(action: {
            self.isSelected.toggle()
        }) {
            Text(isSelected ? "Selected" : "Not Selected")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    @State static var selected: Bool = false

    static var previews: some View {
        ContentView(isSelected: $selected)
    }
}

推荐答案

您没有误解任何东西.当基础@State更改时,使用@Binding的View将更新,但是 @State必须在视图层次结构中定义.(否则您可以绑定到发布者)

You have not misunderstood anything. A View using a @Binding will update when the underlying @State change, but the @State must be defined within the view hierarchy. (Else you could bind to a publisher)

下面,我将您的ContentView的名称更改为OriginalContentView,然后在包含您的原始内容视图的新ContentView中定义了@State.

Below, I have changed the name of your ContentView to OriginalContentView and then I have defined the @State in the new ContentView that contains your original content view.

import SwiftUI

struct OriginalContentView: View {
    @Binding var isSelected: Bool

    var body: some View {
        Button(action: {
            self.isSelected.toggle()
        }) {
            Text(isSelected ? "Selected" : "Not Selected")
        }
    }
}

struct ContentView: View {
    @State private var selected = false

    var body: some View {
       OriginalContentView(isSelected: $selected)
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这篇关于SwiftUI @Binding更新不会刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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