So far, and with help from this forum, I have an app that that lets the user create a favorites list of Drugs. Drug is a struct. I can add and delete instances of the struct. But my question is, how do i select one favorite, and how can i acces the properties of the struct selected import SwiftUI
struct Drug: Identifiable, Codable {
var id = UUID()
var name: String
var amount: String
var unitamount : String
var bag: String
var isRead: Bool = false
}
class Favoritos: ObservableObject {
@Published var favs = [Drug]() {
didSet {
if let encoded = try? JSONEncoder().encode(favs) {
UserDefaults.standard.set(encoded, forKey: "Favs")
}
}
}
init() {
if let savedItems = UserDefaults.standard.data(forKey: "Favs") {
if let decodedItems = try? JSONDecoder().decode([Drug].self, from: savedItems) {
favs = decodedItems
return
}
}
favs = []
}
}
struct FavListView: View {
@StateObject var favoritos = Favoritos()
// @State var newdrug = Drug(name: "", amount: "", bag: "")
@State private var showingAddView = false
func removeItems(at offsets: IndexSet) {
favoritos.favs.remove(atOffsets: offsets)
}
var body: some View {
NavigationView {
VStack{
// List {
// TextField ("Droga", text: $newdrug.name)
// TextField ("Cantidad", text: $newdrug.amount)
// TextField ("Volumen", text: $newdrug.bag)
// }
List
{ ForEach(favoritos.favs) { drug in
Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")
}.onDelete(perform: removeItems)
}.navigationTitle("Infusiones favoritas")
.navigationBarTitleDisplayMode(.inline)
.accentColor(.black)
Button ("agregar nuevo favorito") {showingAddView = true }
// Button ("Add") {
// favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, bag: newdrug.bag), at: 0)
//
//
// }
}.sheet(isPresented: $showingAddView) {
AddView(favoritos: favoritos)
}
}
}
struct FavListView_Previews: PreviewProvider {
static var previews: some View {
FavListView()
}
}
}
import SwiftUI
struct AddView: View { @ObservedObject var favoritos : Favoritos @State var newdrug = Drug(name: "", amount: "", unitamount: "", bag: "") var body: some View { VStack{ List { TextField ("Droga", text: $newdrug.name) .disableAutocorrection(/@START_MENU_TOKEN@/true/@END_MENU_TOKEN@/) TextField ("Cantidad", text: $newdrug.amount) TextField ("Unidad", text: $newdrug.unitamount) .autocapitalization(/@START_MENU_TOKEN@/.none/@END_MENU_TOKEN@/) TextField ("Volumen", text: $newdrug.bag) } } Button ("Add") { favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, unitamount: newdrug.unitamount, bag: newdrug.bag), at: 0) } } }
struct AddView_Previews: PreviewProvider { static var previews: some View { AddView(favoritos : Favoritos()) } }