Skip to content

Instantly share code, notes, and snippets.

@all12jus
Last active October 11, 2022 02:37
Show Gist options
  • Save all12jus/0daa04ca67fbedfd9cb6d0a0d4367ff6 to your computer and use it in GitHub Desktop.
Save all12jus/0daa04ca67fbedfd9cb6d0a0d4367ff6 to your computer and use it in GitHub Desktop.
Number only
//
// TestMoney.swift
// FormButtonTest
//
// Created by Justin Allen on 10/10/22.
//
import SwiftUI
extension String {
public func removingCharacters(in set: CharacterSet) -> String {
let filtered = unicodeScalars.filter { !set.contains($0) }
return String(String.UnicodeScalarView(filtered))
}
}
class NumberOnly: ObservableObject {
let invalidCharacters = CharacterSet(charactersIn: "0123456789.").inverted
let decimalPlaces: Int
init(decimalPlaces: Int) {
self.decimalPlaces = max(0, decimalPlaces)
}
@Published var characters: [Character] = []
@Published var decimalValue: Decimal = 0
@Published var value: String = "" {
didSet {
if value.count == 0 {
characters = []
return
}
var chars : [Character] = Array(value.removingCharacters(in: invalidCharacters))
if chars.count == 0 {
value = ""
characters = []
return
}
while chars.filter({$0 == "."}).count > 1 {
let periodIndex = chars.lastIndex(of: ".")!
print(chars)
chars.removeSubrange(periodIndex..<chars.count)
}
if chars.filter({$0 == "."}).count == 1 {
let periodIndex = chars.lastIndex(of: ".")! + (decimalPlaces + 1)
print(chars)
if chars.count > periodIndex {
chars.removeSubrange(periodIndex..<chars.count)
}
if decimalPlaces == 0 {
chars.removeLast()
}
}
if decimalPlaces != 0 && chars[0] == "." {
chars.insert("0", at: 0)
}
print(chars)
let possibleString = chars.compactMap { "\($0)" }.joined()
print(possibleString)
if value != possibleString {
value = possibleString
}
decimalValue = Decimal(string: value) ?? 0
}
}
}
struct TestMoney: View {
@ObservedObject var stringAmount = NumberOnly(decimalPlaces: 2)
var body: some View {
TextField("0.00", text: $stringAmount.value)
.keyboardType(.decimalPad)
.padding()
}
}
struct TestMoney_Previews: PreviewProvider {
static var previews: some View {
TestMoney()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment