Post

Replies

Boosts

Views

Activity

Reply to Index Out of Range
I changed it to this, but when I press Add, the simulator freezes // // ContentView.swift // Fede // // Created by Jad Taljabini on 14/03/21. // import SwiftUI struct ContentView: View { @State private var media: String = "" @State private var voto: String = "" @State private var voti: [Float] = [] @State private var nVoti: Int = 0 @State private var test: String = "" @State private var voti2: [Float] = [] var body: some View { NavigationView { Form { Section{ TextField("A che media vuoi arrivare", text: $media) } Section{ TextField("Quanti voti prenderai", text: $test) } Section{ HStack { TextField("Tuoi voti", text: $voto) Spacer() Button(action: { voti.append(Float(voto) ?? 0) voto = "" nVoti = nVoti + 1 tutto() }, label: { Text("Add") }) } } Section{ ForEach(voti, id: \.self){ item in Text("\(item, specifier: "%.1f")") }.onDelete(perform: removeRows) } Section(header: Text("Voti che devi prendere")){ ForEach(voti2, id: \.self){ item2 in Text("\(item2)") } } } .navigationTitle("Media") } } func tutto() { let testInt = Int(test) ?? 0 let mediaFloat = Float(media) ?? 0 var mediaEffettiva = mediaEffFunzione(dim: nVoti) if mediaEffettiva mediaFloat { for i in 0..testInt - 2 { voti2[i] = Float(Int(mediaEffettiva + 1)) } let mediaEffettivaInt = Int(mediaEffettiva) let mediaFloatInt = Int(mediaFloat) var con: Int = 0 while(mediaEffettivaInt mediaFloatInt){ for j in nVoti..nVoti + testInt - 2{ voti[j] = voti2[j - nVoti]; } mediaEffettiva = mediaEffFunzione(dim: nVoti + testInt) if mediaEffettiva mediaFloat && voti2.isValidIndex(con) { voti2[con] += 0.5 } con = con + 1 if con = testInt { con = 0 } } } } func removeRows(at offsets: IndexSet) { voti.remove(atOffsets: offsets) } func mediaEffFunzione(dim: Int) - Float { var somma: Float = 0 for i in voti{ somma = somma + i } return somma / Float(dim) } } extension Array { func isValidIndex(_ index: Int) - Bool { return index = 0 && index self.count } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to ForEach and HStack
var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "CoreDataModel") container.loadPersistentStores(completionHandler: {(StoreDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext() { let context = persistentContainer.viewContext if context.hasChanges{ do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } class dataModel: ObservableObject{ @Published var data: [NSManagedObject] = [] //Contiene i dati, tutti i favorites @Published var txt = "" let context = persistentContainer.viewContext init() { readData() } func readData(){ let request = NSFetchRequestNSFetchRequestResult(entityName: "Content") do { let results = try context.fetch(request) self.data = results as! [NSManagedObject] } catch { print(error.localizedDescription) } } func writeData(){ let entity = NSEntityDescription.insertNewObject(forEntityName: "Content", into: context) entity.setValue(txt, forKey: "value") do { try context.save() self.data.append(entity) //txt = "" } catch { print(error.localizedDescription) } } func deleteData(indexSet: IndexSet){ for index in indexSet{ do { let obj = data[index] context.delete(obj) try context.save() let index = data.firstIndex(of: obj) data.remove(at: index!) } catch { print(error.localizedDescription) } } } func updateData(){ } func getValue(obj: NSManagedObject) - String{ return obj.value(forKey: "value") as! String } } class dataModel1: ObservableObject{ @Published var data: [NSManagedObject] = [] //Contiene i dati, tutti i favorites @Published var dataAttuale = Date() let context = persistentContainer.viewContext init() { readData() } func readData(){ let request = NSFetchRequestNSFetchRequestResult(entityName: "Content2") do { let results = try context.fetch(request) self.data = results as! [NSManagedObject] } catch { print(error.localizedDescription) } } func writeData(){ let entity = NSEntityDescription.insertNewObject(forEntityName: "Content2", into: context) entity.setValue(dataAttuale, forKey: "date") do { try context.save() self.data.append(entity) //txt = "" } catch { print(error.localizedDescription) } } func deleteData(indexSet: IndexSet){ for index in indexSet{ do { let obj = data[index] context.delete(obj) try context.save() let index = data.firstIndex(of: obj) data.remove(at: index!) } catch { print(error.localizedDescription) } } } func updateData(){ } func getValue(obj: NSManagedObject) - Date{ return obj.value(forKey: "date") as! Date } } The getValue function returns two different types in the two classes, thats why I need two FoeEach loops
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to ForEach and HStack
@ObservedObject var model = dataModel() @ObservedObject var date = dataModel1() dataModel and dataModel1 are two different classes which contain two different arrays. The two classes have to be sperate. The arrays have the same length because : Button(action: { model.writeData() date.writeData() }) { Image(systemName: "plus") } model.writeData() saves the String that is in the TextFiled and date.writeData()saves the Date.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Comma not working
So, when I press the decimal point button it should add a decimal point, what happens is that when I press the decimal point it doesn't consider the numbers that I write after the decimal point. Sorry for my inaccuracy, I'm still learning and thank you very much
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Append to Double
Sorry, I didn't make myself clear I made a calculator and when I tap the numbers, they don't append to each other, how do I solve it This is what I am doing: // // ContentView.swift // Calcolatrice // // Created by Jad Taljabini on 26/03/21. // import SwiftUI import Combine enum Nums: String{ case uno = "1" case due = "2" case tre = "3" case quattro = "4" case cinque = "5" case sei = "6" case sette = "7" case otto = "8" case nove = "9" case zero = "0" case moltiplicazione = "X" case divisione = "/" case somma = "+" case meno = "-" case uguale = "=" case AC = "AC" case piùMeno = "±" case percentuale = "%" case virgola = "." case niente = "" } struct ContentView: View { var numeri: [[Nums]] = [ [Nums.AC, Nums.piùMeno, Nums.percentuale, Nums.divisione], [Nums.sette, Nums.otto, Nums.nove, Nums.moltiplicazione], [Nums.quattro, Nums.cinque, Nums.sei, Nums.meno], [Nums.uno, Nums.due, Nums.tre, Nums.somma], [Nums.zero, Nums.niente, Nums.virgola, Nums.uguale] ] private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())] @State var res: Double = 0 @State var previousVar: Double = 0 let timer = Timer.publish(every: 0.001, on: .main, in: .common).autoconnect() @State var con: Int = 0 @State var final: Double = 0 @State var operat = Nums(rawValue: "") var body: some View { VStack{ Spacer() HStack{ Spacer() Text("\(res, specifier: "%.2f")") .font(.system(size: 50)) .bold() .padding() } Spacer() LazyVGrid(columns: gridItemLayout, content: { ForEach(0..5){ i in ForEach(0..4){ j in RoundedRectangle(cornerRadius: 35.0) .foregroundColor(.orange) .frame(width: 80, height: 80, alignment: .center) .overlay( Text("\(numeri[i][j].rawValue)") .font(.largeTitle) .foregroundColor(.black) ).onTapGesture { switch numeri[i][j] { case Nums.AC: operat = Nums.AC; res = 0 case Nums.uguale: operat = Nums.uguale; res = final case Nums.somma: operat = Nums.somma; previousVar = res; res = 0; con = 0 case Nums.meno: operat = Nums.meno; previousVar = res; res = 0 con = 0 case Nums.divisione: operat = Nums.divisione; previousVar = res; res = 0; con = 0 case Nums.moltiplicazione: operat = Nums.moltiplicazione; previousVar = res; res = 0; con = 0 case Nums.percentuale: operat = Nums.percentuale; res = res / 100 case Nums.piùMeno: operat = Nums.piùMeno; res = res * -1; con = 0 case Nums.virgola: operat = Nums.virgola; res = Double(String(res) + ".") ?? 0 default: res = Double(numeri[i][j].rawValue) ?? 0 con += 1 } } } } }).onReceive(timer) { _ in if con != 0 { if operat == Nums.divisione{ final = previousVar / res } else if operat == Nums.meno{ final = previousVar - res } else if operat == Nums.moltiplicazione{ final = previousVar * res } else if operat == Nums.somma{ final = previousVar + res } } } }.padding(2) } } At line 115 I am making res equal a number, what I want to do is to append that number to res Thank you
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Mar ’21
Reply to Problems with ForEach, SwiftUI
Errors: Cannot infer key path type from context; consider explicitly specifying a root type Insert '#Root#' Extra arguments at positions #2, #3 in call Generic parameter 'Content' could not be inferred Explicitly specify the generic arguments to fix this issue Missing argument for parameter 'content' in call Insert ', content: #(Int) - _#' Value of type '[UserItalia]' has no member 'weather
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Apr ’21
Reply to Errors in ForEach SwiftUI
Text( "\(networkController.users.main ?? Main(temp: 0).temp)") Gives some errors: Cannot convert value of type 'Float' to expected argument type 'Main' Instance method 'appendInterpolation' requires that 'Main' conform to '_FormatSpecifiable' But yes, (this: Text( "\(networkController.users.main ?? Main(temp: 0).temp)")), this is what I want to do.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Apr ’21