【问题标题】:SwiftUI Combine Why can't bind data in init?SwiftUI Combine 为什么 init 不能绑定数据?
【发布时间】:2020-11-09 16:04:32
【问题描述】:

我正在尝试一个非常简单的测试,将一个简单的 Just("JustValue") 组合到一个属性中。 但它没有用。
↓ 这是我的代码

struct ResponseView: View {
    
    private var contentCancellable: AnyCancellable? = nil
    @State var content: String = "InitialValue"
    
    var body: some View {
        Text(content)
    }

    init() {
        contentCancellable = Just("JustValue").assign(to: \.content, on: self)
    }
}

有谁知道为什么文本显示"InitialValue" 而不是"JustValue"

【问题讨论】:

    标签: swiftui combine


    【解决方案1】:

    这是特定于状态属性包装器初始化传递...外部状态存储是稍后创建的,因此只应用了一次初始化。

    如果你想更新它,稍后再做,当状态已经创建并链接到视图时,比如

    struct ResponseView: View {
        
        @State var content: String = "InitialValue"
        
        var body: some View {
            Text(content)
                .onAppear {
                    _ = Just("JustValue").assign(to: \.content, on: self)
                }
        }
    }
    

    提供您所期望的 UI。

    【讨论】:

    • 感谢 Asperi。这行得通!所以我的代码不能按我的预期工作的原因是在 init 调用时尚未创建 State 属性?
    猜你喜欢
    • 2020-01-10
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2020-03-30
    • 1970-01-01
    • 2022-06-13
    • 2021-06-12
    相关资源
    最近更新 更多