ViewBuilder 内容未因 SwiftUI 中的绑定更改而更新

问题描述 投票:0回答:1

我有一个可选配置

isAttending
,它以
nil
开头。当按下“+”按钮时,它应该将该值设置为提供的默认值,并且选择器应该将其显示为所选值。

但是,按下“+”按钮时,选择器不会突出显示所选值。当前行为:

enter image description here

期望的行为:

enter image description here

注意:如果其他一些 UI 组件发生更改,则选取器会在该渲染周期中更新为正确的视觉状态

import SwiftUI

struct QuestionView<Option, Content: View>: View {
    @Binding var option: Option?
    let defaultOption: Option?
    @ViewBuilder let content: () -> Content

    var body: some View {
        VStack {
            if let _ = option {
                content()
            } else {
                Button {
                    option = defaultOption
                } label: {
                    Label("Add Filter Option", systemImage: "plus")
                        .labelStyle(.iconOnly)
                }
            }
        }
    }
}

struct Config {
    var isAttending: Bool?
}

#Preview {
    @Previewable @State var config: Config = Config()
    QuestionView(option: $config.isAttending, defaultOption: false) {
        Picker("RSVP", selection: $config.isAttending) {
            Text("Attending").tag(true)
            Text("Not Attending").tag(false)
        }
        .pickerStyle(.segmented)
    }
}
swiftui binding
1个回答
0
投票

IMO,你需要使 Config 符合

ObservableObject
,试试这个:

final class Config: ObservableObject {
    @Published var isAttending: Bool?
}

struct ContentView: View {
    @StateObject private var config: Config = Config()
    
    var body: some View {
        QuestionView(option: $config.isAttending, defaultOption: false) {
            Picker("RSVP", selection: $config.isAttending) {
                Text("Attending")
                    .tag(true)
                
                Text("Not Attending")
                    .tag(false)
            }
            .pickerStyle(.segmented)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.