我有一个可选配置
isAttending
,它以 nil
开头。当按下“+”按钮时,它应该将该值设置为提供的默认值,并且选择器应该将其显示为所选值。
但是,按下“+”按钮时,选择器不会突出显示所选值。当前行为:
期望的行为:
注意:如果其他一些 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)
}
}
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)
}
}
}