how to set currency format on a textfield of a class using swift - swift

How to set currency format E.g. 2,000,000.00 in swift on a textfield using swift 3.2 ? I am getting this response when in text field when i am entering amount in textfield
CharacterView(_core: Swift._StringCore(_baseAddress:
Optional(0x00000001c464e38a), _countAndFlags: 13835058055282163718,
_owner: Optional(₹ 75.33)), _coreOffset: 1)
My Code is:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Construct the text that will be in the field if this change is accepted
switch string {
case "0","1","2","3","4","5","6","7","8","9":
currentString += string
formatCurrency(currentString)
default:
if string.characters.count == 0 && currentString.characters.count != 0 {
currentString = String(currentString.characters.dropLast())
formatCurrency(currentString)
}
}
return false }
func formatCurrency(_ string: String) {
print("format \(string)")
print(txtfieldamount.text!)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
//formatter.locale = findLocaleByCurrencyCode("NGN")
let numberFromField = (NSString(string: currentString).doubleValue)/100
let temp = formatter.string(from: NSNumber(value: numberFromField))
self.txtfieldamount.text! = String(describing: temp!.characters.dropFirst())
print(txtfieldamount.text!)
}

Related

UITextField: backspace doesn't delete the first character

I have a UITextField with a formatted string.
I can't figure out why a backspace press works fine for every character deletion except the first character?
My code:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = NumberFormatter()
formatter.usesGroupingSeparator = true
formatter.numberStyle = .decimal
formatter.decimalSeparator = "."
formatter.groupingSeparator = " "
let textString = textField.text ?? ""
guard let range = Range(range, in: textString) else { return false }
let updatedString = textString.replacingCharacters(in: range, with: string)
let completeString = updatedString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
guard let value = Double(completeString) else { return false }
numberFromTextField = value
let formattedNumber = formatter.string(from: NSNumber(value: value)) ?? ""
textField.text = formattedNumber
return string == formatter.decimalSeparator
}
A gif with the problem behaviour: CLICK
Where is my error hides?

specify a maximum Value for a UITextField in Swift

I need to specify a maximum value for a text field. I already got an answer from another post on how to restrict a UITextField to numbers only. But I would like to modify that function to only accept a number between 0 and 540.
Is there any way to modify that function?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
guard !s.isEmpty else { return true }
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
return numberFormatter.number(from: s)?.intValue != nil
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(string)
let myRange = 0...540
//ro delete/remove values in textField
if string == "" {
return true
}
let fullText = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
if let wholeNumber = Int(fullText), myRange.contains(wholeNumber) {
return true
}
return false
}
You can check if number lies between 0 and 540.
if let number = numberFormatter.number(from: s)?.intValue {
return number > 0 && number < 540
} else {
return true
}

Maximum number of characters as well as limiting only numeric values in UITextField

Is there a way to limit a UITextField to only numeric value as well as limiting the length.
I have the below two functions but don't know how I can use the shouldChangeCharactersIn twice in the same delegate. Any ideas how to use both of these
// Allow Numeric Only in Quantity
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowCharacters = ".-+1234567890"
let allowedCharacterSet = CharacterSet(charactersIn: allowCharacters)
let typedCharacterSet = CharacterSet(charactersIn: string)
return allowedCharacterSet.isSuperset(of: typedCharacterSet)
}
// Limit the length of the input
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 20
}
Many Thanks
You can do it like this
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
let allowedCharacters = ".-+1234567890"
let allowedCharcterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharcterSet = CharacterSet(charactersIn: string)
if allowedCharcterSet.isSuperset(of: typedCharcterSet)
, count <= 20 {
return true
} else {
return false
}
}
Or you can use this Subclass of UITextField
class JDTextField: UITextField {
#IBInspectable var maxLength: Int = 0 // Max character length
var valueType: ValueType = ValueType.none // Allowed characters
/************* Added new feature ***********************/
// Accept only given character in string, this is case sensitive
#IBInspectable var allowedCharInString: String = ""
func verifyFields(shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch valueType {
case .none:
break // Do nothing
case .onlyLetters:
let characterSet = CharacterSet.letters
if string.rangeOfCharacter(from: characterSet.inverted) != nil {
return false
}
case .onlyNumbers:
let numberSet = CharacterSet.decimalDigits
if string.rangeOfCharacter(from: numberSet.inverted) != nil {
return false
}
case .phoneNumber:
let phoneNumberSet = CharacterSet(charactersIn: "+0123456789")
if string.rangeOfCharacter(from: phoneNumberSet.inverted) != nil {
return false
}
case .alphaNumeric:
let alphaNumericSet = CharacterSet.alphanumerics
if string.rangeOfCharacter(from: alphaNumericSet.inverted) != nil {
return false
}
case .fullName:
var characterSet = CharacterSet.letters
print(characterSet)
characterSet = characterSet.union(CharacterSet(charactersIn: " "))
if string.rangeOfCharacter(from: characterSet.inverted) != nil {
return false
}
}
if let text = self.text, let textRange = Range(range, in: text) {
let finalText = text.replacingCharacters(in: textRange, with: string)
if maxLength > 0, maxLength < finalText.utf8.count {
return false
}
}
// Check supported custom characters
if !self.allowedCharInString.isEmpty {
let customSet = CharacterSet(charactersIn: self.allowedCharInString)
if string.rangeOfCharacter(from: customSet.inverted) != nil {
return false
}
}
return true
}
}
How to use it
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Verify all the conditions
if let sdcTextField = textField as? JDTextField {
return sdcTextField.verifyFields(shouldChangeCharactersIn: range, replacementString: string)
} else {
return true
}
}
And in viewDidLoad() you set characteristics in just one line
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.textField.delegate = self
self.textField.maxLength = 10
self.textField.allowedCharInString = ".-+1234567890"
}

Set max length UITextField

How to limit the number of characters in a UITextField?
I need to to display max 10 characters
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCadena = textField.text, let range = Range(range, in: textFieldCadena) else {
return false
}
let nuevaCadena = textFieldCadena.replacingCharacters(in: range, with: string)
if nuevaCadena.isEmpty {
textField.text = "0"
return false
} else if textField.text == "0" {
textField.text = string
return false
}
if textField == textField {
let allowedCharacters = CharacterSet(charactersIn:"0123456789 ")
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
As decribed here You can use .maxlength in swift 5 to set character length. Credit to article here:
https://www.swiftdevcenter.com/max-character-limit-of-uitextfield-and-allowed-characters-swift/
self.textField.maxLength = 10
Do the check for character count first
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard
let textFieldCadena = textField.text,
let range = Range(range, in: textFieldCadena),
textFieldCadena.count <= 10
else { return false }
...
}

Swift: Show $ and comma in the decimal textfield input

I have a few textfields with decimal keyboards, I want to make them showing $ and comma ($1,222,000.00) in the screen. And also change the spacing of the text because when added comma it will be crowded.
for textField in self.numberTextField! as [UITextField] {
textField.keyboardType = .DecimalPad
textField.inputAccessoryView = keyboardToolbar
numberTextField is my collection of the textfields. Any help appreciated! Thanks a lot!
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
var newText = oldText.stringByReplacingCharactersInRange(range, withString: string) as NSString!
var newTextString = String(newText)
let digits = NSCharacterSet.decimalDigitCharacterSet()
var digitText = ""
for c in newTextString.unicodeScalars {
if digits.longCharacterIsMember(c.value) {
digitText.append(c)
}
}
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let numberFromField = (NSString(string: digitText).doubleValue)/100
newText = formatter.stringFromNumber(numberFromField)
textField.text = String(newText)
return false
}