SwiftUI:无法绑定到Picker中结构中的对象
我正在创建一个可重用的TestView,但无法将结构的属性绑定到选择器。在本例中,我试图绑定到@State对象 其思想是从SwiftUI:无法绑定到Picker中结构中的对象,swiftui,Swiftui,我正在创建一个可重用的TestView,但无法将结构的属性绑定到选择器。在本例中,我试图绑定到@State对象 其思想是从jobListViewModel提供的频道列表中选择一个频道 代码: 但是,从选择器中选择任何通道后,选择器不会显示选定的通道。如何将通道从jobListViewModel绑定到选择器?通常,嵌套的observeObjects可能会有问题。我还将考虑使用Picker而不是整个对象来存储您选择的频道的id struct TestObject: Codable, Identifi
jobListViewModel
提供的频道列表中选择一个频道
代码:
但是,从选择器中选择任何通道后,选择器不会显示选定的通道。如何将通道从
jobListViewModel
绑定到选择器?通常,嵌套的observeObject
s可能会有问题。我还将考虑使用Picker
而不是整个对象来存储您选择的频道的id
struct TestObject: Codable, Identifiable {
@DocumentID var id = UUID().uuidString
var channel: Channel?
}
struct Channel: Codable, Identifiable, Hashable {
@DocumentID var id = UUID().uuidString
var name: String
}
struct TestView: View {
var jobListViewModel: JobListViewModel
@State var testObject: TestObject
var body: some View {
NavigationView {
Form {
Section() {
Picker("Post to", selection: $testObject.channel) {
ForEach(jobListViewModel.channelViewModels, id: \.id) { (vm) in
Text(vm.channel.name)
}
}
}
}
}
}
}
class JobListViewModel: ObservableObject {
//Channels
@Published var channelsRepository = ChannelsRepository()
@Published var channelViewModels = [ChannelViewModel]()
private var cancellables = Set<AnyCancellable>()
init() {
channelsRepository.$channels
.map { (channels) in
channels.map {ChannelViewModel(channel: $0)}
}
.assign(to: \.channelViewModels, on: self)
.store(in: &cancellables)
}
}
class ChannelViewModel: ObservableObject, Identifiable {
@Published var channel: Channel
var id = ""
private var cancellables = Set<AnyCancellable>()
init(channel: Channel) {
self.channel = channel
$channel
.compactMap { (channel) in
channel.id
}
.assign(to: \.id, on: self)
.store(in: &cancellables)
}
}
//In ContentView
.sheet(item: $activeSheet) { (sheet) in
switch sheet {
case .testSheet:
let testObject = TestObject(channel: jobListViewModel.channelViewModels.first?.channel)
TestView(jobListViewModel: jobListViewModel, testObject: testObject)
}
}