Hello
When I tap on my TextField more than 2/4 times the app crashes
Before that I get these errors:
2020-12-29 11:28:10.265525+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-PadDefault
2020-12-29 11:28:18.778004+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-PadDefault
2020-12-29 11:28:22.268833+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-Pad_Default
Then after 2/4 four times tapping on the TextField the app crashes and I get this error
2020-12-29 11:28:22.419634+0100 Nums[1670:295112] [error] precondition failure: attribute being read has no value: 768444
AttributeGraph precondition failure: attribute being read has no value: 768444.
(lldb)
Here is the TextField:
GroupBox {
						HStack {
							 TextField("Have a goal?", text: $saveGoal.bound)
									 .keyboardType(.numberPad)
									Spacer()
						Button(action: {
						UserDefaults.standard.set(self.saveGoal, forKey: "Save")																		UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
																}) {		
																		Text("Save")
																}
												}
										}.padding(.top).padding(.trailing).padding(.leading)
Thank you for your time
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
I don't get any error when I fetch data but when I run I don't see any data
Thank you
import SwiftUI
import Combine
struct ContentView: View {
		@ObservedObject var networkController = NetworkController()
		@State var search: String = ""
		var body: some View {
				NavigationView{
						Form{
								Section(){
										TextField("Search", text: $search)
								}
								Section(){
										List(networkController.users.filter {
														$0.state.contains(search) }
												 , id: \.state){ user in
												Text(user.state)
										}
								}
						}
						.navigationTitle("API")
				}
		}
}
class NetworkController: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://api.covidtracking.com/v1/states/current.json")!
		@Published var users = [User(state: "")]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [User].self, decoder: JSONDecoder())
						.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct User: Decodable {
		var state: String
}
Hello
I'm trying to decode a JSON File but it's not working and I can't understand why
Code:
import SwiftUI
struct Search: View {
let sf: [SF] = Bundle.main.decode("sf.json")
@State private var searchText: String = ""
var body: some View {
NavigationView{
Form {
Section(header: Text("Search bar")){
TextField("Search", text: $searchText)
.padding(7)
.background(Color(.systemGray6))
.cornerRadius(8)
}
Section(){
List{
ForEach(sf) { item in
Text(item.title)
}
}
}
}
.navigationTitle("SF")
}
}
}
struct SF: Codable, Identifiable {
var id: String
var title: String
var items: [String]
}
extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
Here is the JSON file
[
{
"id": "all"
"title": "All",
"items": [
"square.and.arrow.up",
"square.and.arrow.up.fill",
"square.and.arrow.down"
]
}
]
Thank you
Hello
Do you know why the comma in this calculator app isn't working:
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 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: "")
@State var digits: String = "0"
var res: Double {
get {
//digits.hasSuffix(".") ? Double(digits.dropLast()) ?? 0.0 : Double(digits) ?? 0.0
digits.hasSuffix(".") ? Double(digits) ?? 0.0 : Double(digits) ?? 0.0
}
nonmutating set {
digits = String(format: "%.10g", newValue) //- May need better formatting
}
}
var body: some View {
VStack{
Spacer()
HStack{
Spacer()
Text("\(digits)")
.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;
if digits.hasPrefix("-") {
digits = String(digits.dropFirst())
} else {
digits = "-" + digits
}
con = 0
case Nums.virgola:
operat = Nums.virgola;
if !digits.contains(".") {
digits += "."
}
default:
if digits == "0" {
digits = numeri[i][j].rawValue
} else {
digits += numeri[i][j].rawValue
}
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)
}
}
Maybe at line 51 and 52 or 121
(If you can explain my mistakes all around the code I would be grateful)
Thank you
Hello
I'm trying to fetch some data from a JSON Api, but when I access the properties of my struct it tells me Value of Type "Name Of The Struct" has no member "name of the property"
Any idea on how to fix it
Code:
import SwiftUI
import Combine
struct ContentView: View {
		
		@ObservedObject var networkController = NetworkControllerItalia()
		var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		var body: some View {
				NavigationView{
						ScrollView{
								ForEach(networkController.users, id: \.self){ user in
										GroupBox(label: Text(user.round ?? ""), content: {
												VStack{
														Text(user.team1 ?? "")
												}
										}).padding()
						}
						.navigationTitle("Serie A")
				}
		 }
	 }
}
class NetworkControllerItalia: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/it.1.json")!
		//let url = URL(string: "google.com")!
		@Published var users = [UserItalia(matches: [])]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [UserItalia].self, decoder: JSONDecoder())
						//.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveCompletion: {completion in
								print(completion)
						}, receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct UserItalia: Decodable, Hashable {
		var matches: [Matches]?
}
struct Matches: Decodable, Hashable {
		var round: String?
		var date: String?
		var team1: String?
		var team2: String?
}
Thank You
Hello
Is there any way to put the 2 Texts in an HStack without putting the 2 ForEachs together?
Code:
ForEach(model.data, id: \.objectID){ obj in
Text(model.getValue(obj: obj))
}.onDelete(perform: model.deleteData)
ForEach(date.data, id: \.objectID){ obj1 in
Text("\(date.getValue(obj: obj1), formatter: dateFormatter)")
}.onDelete(perform: date.deleteData)
Thank you
Hello
I made a custom Picker View but I don't have any idea on how to change the background color to grey when I press on one of the options
Here is the code:
struct PickerView: View {
		
		var arr: [String] = ["Easy", "Medium", "Hard"]
		var h: CGFloat = 50
		var w: CGFloat = 320
		
		@ObservedObject var input: UserInput
		var body: some View{
				HStack(spacing: 40){
						ForEach(0..<arr.count){ i in
								HStack(spacing: 25){
										Text(arr[i])
												.bold()
												.onTapGesture {
														switch i{
														case i: input.indi = i
														default: return
														}
														print(i)
												}
										if(i < arr.count - 1){
										Divider()
												.frame(height: 25)
										}
								}
						}
				}.padding()
				.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
				.overlay(
						RoundedRectangle(cornerRadius: 16)
								.stroke(Color.gray, lineWidth: 3)
				)
		}
}
class UserInput: ObservableObject {
		@Published var indi: Int = 0
}
Thank you for your time
Hello
I have a Raindrop shape:
struct Raindrop: Shape {
func path(in rect: CGRect) - Path {
Path { path in
path.move(to: CGPoint(x: rect.size.width / 2, y: 0))
path.addQuadCurve(to: CGPoint(x: rect.size.width / 2, y: rect.size.height), control: CGPoint(x: rect.size.width, y: rect.size.height))
path.addQuadCurve(to: CGPoint(x: rect.size.width / 2, y: 0), control: CGPoint(x: 0, y: rect.size.height))
}
}
}
When I trim it in the ContentView, it trims from right to left, is there a way to trim it from top to bottom?
Raindrop()
.trim(from: 0.9, to: 1)
.scaledToFit()
Thank you
Hello
How do I solve the Index out of range at line 81
I tried many ways, but none of them worked
//
// 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] = []
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
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
}, 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)")
}
}
}.onReceive(timer) { input in
voti2 = tutto()
}
.navigationTitle("Media")
}
}
func tutto() - [Float] {
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[con] += 0.5
}
con = con + 1
if con = testInt {
con = 0
}
}
}
return voti2
}
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)
}
}
Thank you very much
Hello
If I have this array:
var objects = [
Object(value: 100, date: Date(), imageTemplate: "30"),
Object(value: 200, date: Date(), imageTemplate: "20"),
Object(value: 400, date: Date() + 84000, imageTemplate: "10")
]
How can I count how many different dates are in the array using NSPredicate?
In this case it should return 2.
Thank You!
Hello
import SwiftUI
enum When: String {
case Today
case Week
case Month
case Year
}
struct ChartView: View {
var when: When
@EnvironmentObject var millilitriInseritiModel: MillilitriInseritiModel
var valoriAsseX: [String]{
if when == When.Week{
return ["M", "T", "W", "T", "F", "S", "S"]
} else if when == When.Month{
return ["7", "14", "21", "28"]
} else if when == When.Year{
return ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]
}
return []
}
var valoriAsseY: [Double]{
return []
}
var dates: [Date] = [Date(), Date().addingTimeInterval(86400), Date().addingTimeInterval(86400 * 2)]
@State var valori: [Double] = [1000, 2000, 3000, 1000, 2000, 1000, 2000, 3000, 1000, 2000, 3000]
var altezzaRettangolo: [Double]?{
var altezze: [Double] = []
for i in 0..<valori.count{
altezze.append(valori[i])
}
return altezze
}
@State var animation: Bool = false
var body: some View{
HStack(alignment: .bottom, spacing: 8, content: {
ForEach(valoriAsseX.indices){ i in
VStack{
RoundedRectangle(cornerRadius: 3)
.fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .top, endPoint: .bottom))
.frame(width: 40, height: animation ? CGFloat(altezzaRettangolo?[i] ?? 0) / 7 : 0)
.animation(.easeInOut)
Text(valoriAsseX[i])
.fontWeight(.semibold)
.multilineTextAlignment(.leading)
.onTapGesture {
withAnimation{
valori[i] += 100
}
}
}
}
})
.padding()
.onAppear {
animation = true
}
.onDisappear {
animation = false
}
}
}
struct ChartView_Previews: PreviewProvider {
static var previews: some View {
ChartView(when: When.Year)
}
}
As you might notice, in the previews I set when to When.Year, that is crashing the app because the array valoriAsseX is bigger than the array altezzaRettangolo, so when I iterate it in the ForEach loop it crashes, I can't find any way to solve this, I tried an if let but it is crashing anyway, any ideas?
Thank you
Hello
I want to be able to save Date in @AppStorage, and it works however I was wondering what was the difference between these two extensions, which one is better and why?
extension Date: RawRepresentable {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
public var rawValue: String {
Date.dateFormatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.dateFormatter.date(from: rawValue) ?? Date()
}
}
and
extension Date: RawRepresentable {
private static let formatter = ISO8601DateFormatter()
public var rawValue: String {
Date.formatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.formatter.date(from: rawValue) ?? Date()
}
}
Thank You!
Hello
I wanted to know why when I print(Date()) the date is printed but two hours before?
Example
If I print(Date()) and the actual date is 2021-09-10 22:33:41 +0000, it prints 2021-09-10 20:33:41 +0000 instead of 2021-09-10 22:33:41 +0000.
Why does this happen?
Thank You!
Hello
How can I remove the Collapse button that is on the navigationBar in iPadOS?
Thank You!
Hello
Is there a view to loop different views, for example in a ForEach loop
Here is what I mean:
import SwiftUI
struct ContentView: View {
		@State var view1 = false
		@State var view2 = false
		@State var view3 = false
		@State var view4 = false
		
		private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		
		var textSize: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 48
				}
				return 23
		}
		
		var title: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 60
				}
				return 34
		}
		
		var height: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 0.15
				}
				return 0.15
		}
		
		var weight: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 0.44
				}
				return 0.43
		}
		
		var body: some View {
				NavigationView{
						GeometryReader { geometry in
								ScrollView(.vertical, showsIndicators: true) {
										LazyVGrid(columns: gridItemLayout, spacing: 18){
												Group{
														Text("View1")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view1 = true
														}
														
														.sheet(isPresented: $view1) {
																View1()
														}
														
														Text("View2")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view2 = true
														}
														
														.sheet(isPresented: $view2) {
																View2()
														}
														
														Text("View3")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view3 = true
														}
														
														.sheet(isPresented: $view3) {
																View3()
														}
														
														Text("View4")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view4 = true
														}
														
														.sheet(isPresented: $view4) {
																View4()
														}
														
														
												}
												
										}.padding()
										
								}
								
						}
						.navigationTitle("Title")
						
				}
		}
		
		
}
Is there a way to put the 4 views in a loop instead of making four different Text Views(they are different views)
Thank your for your time