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
Post
Replies
Boosts
Views
Activity
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
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 don't know why but when I put a List before my ForEach loop, all the text disappears
Code:
//
import SwiftUI
struct SearchDetailView: View {
var sf: SF
var body: some View {
ScrollView{
ForEach(sf.items, id: \.self) { item in
HStack{
Image(systemName: item)
Text(item)
}
}
.navigationTitle(sf.title)
}
}
}
Thank you for your time
Hello
How di i fix the error at line 16: I
nstance member 'deci' cannot be used on type 'BMIView'; did you mean to use a value of this type instead?
import SwiftUI
struct BMIView: View {
@State var deci = "3"
var numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.locale = Locale.current
nf.numberStyle = .decimal
nf.maximumFractionDigits = Int(deci) ?? 0
return nf
}()
@State private var height = ""
@State private var weight = ""
@Environment(\.presentationMode) var presentationMode
var inputAfterConvertions: Double {
//Use NumberFormatter to read numeric values
let hh = numberFormatter.number(from: height)?.doubleValue ?? 0 //<-
let ww = numberFormatter.number(from: weight)?.doubleValue ?? 0 //<-
var ris: Double = 0
if hh > 0 && ww > 0{
ris = (ww / (hh * hh)) * 10000
return ris
}
return 0
}
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your height in cm")){
TextField("Input",text: $height)
.keyboardType(.decimalPad)
}
Section(header: Text("Enter your Weight in kg")){
TextField("Input",text: $weight)
.keyboardType(.decimalPad)
}
Section(header: Text("Check result")){
Text("\(inputAfterConvertions as NSNumber, formatter: numberFormatter)") //<-
}
}
.navigationTitle("BMI")
}
}
}
Thank you
Hello
How do I make the default placeholder of a CustomTextField (that has a double binding) a string (onAppear)
When I run the app on the TextField I see 0 instead of "Input"
Code:
import SwiftUI
struct BMIView: View {
var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = .current
formatter.numberStyle = .decimal
return formatter
}
@State private var height: Double?
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your height in cm")){
DecimalTextField("Input", value: $height.bound, formatter: currencyFormatter)
}
}
.navigationBarTitle("BMI")
}
}
}
struct DecimalTextField: UIViewRepresentable {
private var placeholder: String
@Binding var value: Double
private var formatter: NumberFormatter
init(_ placeholder: String,
value: Binding<Double>,
formatter: NumberFormatter ) {
self.placeholder = placeholder
self._value = value
self.formatter = formatter
}
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = .decimalPad
textfield.delegate = context.coordinator
textfield.placeholder = placeholder
textfield.text = formatter.string(for: value) ?? placeholder
textfield.textAlignment = .left
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done,
target: self, action: #selector(textfield.doneButtonTapped(button:)))
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,
target: nil,action: nil)
toolBar.setItems([space, doneButton], animated: true)
textfield.inputAccessoryView = toolBar
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
// Do nothing, needed for protocol
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: DecimalTextField
init(_ textField: DecimalTextField) {
self.parent = textField
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// Allow only numbers and decimal characters
let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
let withDecimal = (
string == NumberFormatter().decimalSeparator &&
textField.text?.contains(string) == false
)
if isNumber || withDecimal,
let currentValue = textField.text as NSString?
{
// Update Value
let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
let decimalFormatter = NumberFormatter()
decimalFormatter.locale = Locale.current
decimalFormatter.numberStyle = .decimal
// Try currency formatter then Decimal formatrer
let number = self.parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
// Set Value
let double = number.doubleValue
self.parent.value = double
}
return isNumber || withDecimal
}
func textFieldDidEndEditing(_ textField: UITextField,
reason: UITextField.DidEndEditingReason) {
// Format value with formatter at End Editing
textField.text = self.parent.formatter.string(for: self.parent.value)
}
}
}
// MARK: extension for done button
extension UITextField{
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}
extension Optional where Wrapped == Double {
var _bound: Double? {
get{
return self
}
set{
self = newValue
}
}
var bound: Double {
get{
return _bound ?? 0
}
set {
_bound = newValue
}
}
}
The problem might be at line 243
(I found the struct DecimalTextField on the internet)
Thank you for your time
Hello
I wanted to ask if you know where I can start learning CoreML CreateML and integrate them with SwiftUI (NO UIKit please)
Thank You
Hello
I have two questions: I'm using a decimalpad keyboard and when I use the comma the app doesn't recognise it
How do I dismiss the keyboard?
I want that in every country the decimals are written with the comma ( , )
(Can you please write the solution if you know it, thank you for your time)
Code:
import SwiftUI
struct BMIView: View {
@State private var height = ""
@State private var weight = ""
@Environment(\.presentationMode) var presentationMode
var inputAfterConvertions: Float {
let hh = Float(height) ?? 0
let ww = Float(weight) ?? 0
var ris: Float = 0
if hh > 0 && ww > 0{
ris = (ww / (hh * hh)) * 1000
return ris
}
return 0
}
var health: String{
if inputAfterConvertions < 18.49 && inputAfterConvertions > 0 {
return ""
}
else if inputAfterConvertions > 18.5 && inputAfterConvertions < 24.99{
return ""
} else if inputAfterConvertions > 25{
return ""
}
return ""
}
@State var isWriting: Bool = false
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your height in cm")){
TextField("Input",text: $height)
.keyboardType(.decimalPad)
}
Section(header: Text("Enter your Weight in kg")){
TextField("Input",text: $weight)
.keyboardType(.decimalPad)
}
Section(header: Text("Check result")){
Text("\(inputAfterConvertions, specifier: "%.2f")")
}
}
.navigationBarTitle("BMI")
.navigationBarItems(trailing:
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "xmark").font(.title).foregroundColor(.blue)
}
)
}
}
}
Thank you very much for your time
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
When I dismiss my .sheet it is very slow and sometimes it doesn't work
.sheet(isPresented: $myViewi) {
MyView()
}
@Environment(\.presentationMode) var presentationMode
.navigationBarItems(trailing:
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "xmark").font(.title).foregroundColor(.blue)
}
)
How do I fix it?
Thank You
Hello
When I write decimal numbers in my SwiftUI app, the app doesn't detect the comma ( , )
How do I solve it? (I'm using a DecimalPad)
Thank you
Hello
I'm making an app that displays large Double numbers, for example 86,859.002. The problem is how do I change the comma( , ) with the dot ( . )
Thank you
Hello
I created a QR (view) code generator with a "favourites" button and I want to be able to save the String that the user inputs in the favourites view. How can I do it? (And I'm not good at Core Data, so i don't know how to save it)
import SwiftUI
import CoreImage.CIFilterBuiltins
struct QRView: View {
let context = CIContext()
var filter = CIFilter.qrCodeGenerator()
@State var url: String = ""
@Binding var isPresentedQR: Bool
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your Input value")){
TextField("Input",text: $url)
.autocapitalization(.none)
}
Section(header: Text("QR Code")){
Image(uiImage: generatedQRCodeImage(url: url))
.resizable()
.interpolation(.none)
.frame(width: 250, height: 250, alignment: .center)
}
Section{
HStack{
Button(action: {
//What to put here
}) {
HStack{
Text("Add to Favorites")
Spacer()
Image(systemName: "bookmark")
.frame(width: 25, height: 25)
.clipShape(Circle())
}
}
}
}
}
.navigationTitle("QR")
.navigationBarItems(trailing:
Button(action: {
isPresentedQR = false
}) {
Text("Back")
}
)
}
}
func generatedQRCodeImage(url: String) -> UIImage {
let data = Data(url.utf8)
filter.setValue(data, forKey: "inputMessage")
if let qrCodeImage = filter.outputImage{
if let qrCodeCGImage = context.createCGImage(qrCodeImage, from: qrCodeImage.extent){
return UIImage(cgImage: qrCodeCGImage)
}
}
return UIImage(systemName: "xmark") ?? UIImage()
}
}
struct Favorites: View {
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .center, spacing: 20) {
}
.navigationBarTitle("Favorites")
}
}
}
Thank you