У меня есть класс представления, показывающий список элементов, поступающих из класса ViewModel, в окне выбора Начальным состоянием этого средства выбора является первый элемент из массива объектов класса viewModel.
При выборе элемента из средства выбора я хочу выполнить в этом представлении различные действия - 1. отправить информацию об объекте на другой экран по нажатию кнопки. 2. отобразить информацию о выбранном объекте из средства выбора.
import SwiftUI
import Combine
struct SetConfiguration: View {
@ObservedObject var profileListVM : ProfilesListViewModel = ProfilesListViewModel()
@State private var selectedConfiguration = 0 ///show "Add" as initial state
var body: some View {
HStack {
Text("Configuration:")
Picker(selection: $selectedConfiguration.onChange(connectToConfiguration), label: EmptyView()) {
ForEach(profileListVM.profiles, id: \.self) {
choice in
Text(choice.name).tag(choice)
}
}
Text (“Selcted item is: \(self. selectedconfiguration.name)”)
Button(action: {
}) {
Text("Edit")
}.sheet(isPresented: $showEditConfig) {
EditConfigurationView()
// TODO pass selectedConfiguration as profile object
}
}
}
класс viewModel:
class ProfilesListViewModel: ObservableObject {
@Published var profiles: [ProfileViewModel] = [ProfileViewModel]()
static var addNewProfile = ProfileViewModel(name: "Add Configuration")
init() {
fetchAllProfiles()
}
func fetchAllProfiles() {
profiles.append(ProfilesListViewModel.addNewProfile) ///Add is first object
self.profiles = CoreDataManager.shared.getConfigurations().map(ProfileViewModel.init) /// fetch all profile objects
}
}