@Claude31
Here is what I get in console:
Put print statements before check on how much math symbols string has:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//all possible math operation symbols user can add
let symbolsSet = Set(["+","-","x","/"])
var amountOfSymbols = 0
let numberString = textField.text ?? ""
guard let range = Range(range, in: numberString) else { return false }
let updatedString = numberString.replacingCharacters(in: range, with: string)
let correctDecimalString = updatedString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
let completeString = correctDecimalString.replacingOccurrences(of: formatter.decimalSeparator, with: ".")
//current math symbol user add
let symbol = symbolsSet.filter(completeString.contains).last ?? ""
//if user add math symbol to an empty string - do not insert
if string == symbol, numberString.count == 0 { return false }
print("symbol", symbol)
print("string", string)
print("updatedString", updatedString)
print("correctDecimalString", correctDecimalString)
print("completeString", completeString)
//count how much math symbols string has. If more that one - do not insert, string can have only one
completeString.forEach { character in
if symbolsSet.contains(String(character)) {
amountOfSymbols += 1
}
}
if amountOfSymbols > 1 { return false }
}
Here is the console output after each character I type:
Press 2
symbol
string 2
updatedString 2
correctDecimalString 2
completeString 2
Press +
symbol +
string +
updatedString 2+
correctDecimalString 2+
completeString 2+
Press -
symbol +
string -
updatedString 2+-
correctDecimalString 2+-
completeString 2+-
2.Put print statements after check on how much math symbols string has:
if amountOfSymbols > 1 { return false }
print("symbol", symbol)
print("string", string)
print("updatedString", updatedString)
print("correctDecimalString", correctDecimalString)
print("completeString", completeString)
Here is the console output after each character I type:
Press 2
symbol
string 2
updatedString 2
correctDecimalString 2
completeString 2
Press +
symbol +
string +
updatedString 2+
correctDecimalString 2+
completeString 2+
Press -
Nothing is printed
Topic:
UI Frameworks
SubTopic:
UIKit
Tags: