I want to restrict what is entered into a UITextView to Doubles, each Double separated by a space. Of course this means that only one decimal point is allowed.
The following code removes letters and symbols, but does not work for decimals. After entering a decimal point, the next character typed deletes the decimal point.
What am I doing wrong???
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var dataInputField: UITextView!
var currentEntryHasDecimalPoint:Bool = false
var validChars: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", " "]
override func viewDidLoad() {
super.viewDidLoad()
dataInputField.delegate = self
}
func textViewDidChange(_ textView: UITextView ) {
if let str = dataInputField.text, !str.isEmpty {
let validChar:Bool = Set(str).isSubset(of: validChars)
if validChar {
let newChar = str.last!
switch newChar {
case ".":
currentEntryHasDecimalPoint = true
validChars.remove(".")
case " ":
currentEntryHasDecimalPoint = false
validChars.insert(".")
default:
print("default")
}
}
else {
dataInputField.deleteBackward()
}
}
}
}