How can Calculations recognise "," (comma) in a inserted textfield?
Why im asking is because .keyboardType(.decimalPad) has a (decimal dot) "." but in Austria for example a "," (comma) is set automatically by the OS. If this is inserted in a Textfield it breaks the Calculation. With decimal dot "." everything works fine.
Also don't exactly know how to use NSNumberFormatter. Found a simmilar topic about this but none of the solutions worked.
UserData:
import SwiftUI
import Combine
class UserData : ObservableObject {
private static let userDefaultBuyingPrice = "BuyingPrice"
private static let userDefaultRent = "Rent"
private static let userDefaultlivArea = "livArea"
@Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBuyingPrice) ?? "" {
didSet {
UserDefaults.standard.set(self.BuyingPrice, forKey: UserData.userDefaultBuyingPrice)
}
}
@Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? "" {
didSet {
UserDefaults.standard.set(self.Rent, forKey: UserData.userDefaultRent)
}
}
@Published var livArea = UserDefaults.standard.string(forKey: UserData.userDefaultlivArea) ?? "" {
didSet {
UserDefaults.standard.set(self.livArea, forKey: UserData.userDefaultlivArea)
}
}
private var canc: AnyCancellable!
}
ContentView:
import SwiftUI
struct ContentView: View {
@EnvironmentObject var userData: UserData
var sqmPrice: Double{
let price = Double(userData.BuyingPrice) ?? 0
let area = Double(userData.livArea) ?? 0
let sqmPrice = price / area
return sqmPrice
}
var sqmMonth: Double{
let rent = Double(userData.Rent) ?? 0
let area = Double(userData.livArea) ?? 0
let sqmMonth = rent / area
return sqmMonth
}
var body: some View {
VStack {
HStack{
Text ("Price €")
Spacer()
Text ("\(sqmPrice.isNaN ? 0 : sqmPrice, specifier: "%.1f") € /m²")
}
TextField("100.000 €", text: $userData.BuyingPrice)
.font(.title)
.keyboardType(.decimalPad)
}
VStack {
HStack{
Text ("Net Rent €")
Spacer()
Text ("\(sqmMonth.isNaN ? 0 : sqmMonth, specifier: "%.1f") € /m²")
}
TextField("500 €", text: $userData.Rent)
.font(.title)
.keyboardType(.decimalPad)
}
VStack{
HStack{
Text ("Area")
Spacer()
Text ("m²")
}
TextField("50", text: $userData.livArea)
.font(.title)
.keyboardType(.decimalPad)
}
}
Thanks for taking your time.