Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// CurencyTextField.swift
// TestEnv
//
// Created by Yigit Serin on 4.08.2016.
// Copyright © 2016 Yigit Serin. All rights reserved.
//
import UIKit
class CurencyTextField: UIViewController {
@IBOutlet weak var textField: UITextField!
let digitsAfterComma = 2
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidChange(sender: UITextField){
sender.text = removeSpecialCharsFromString(sender.text!)
sender.text = addCharacters(sender.text!)
}
func removeSpecialCharsFromString(text: String) -> String {
let okayChars : Set<Character> =
Set("0123456789".characters)
return String(text.characters.filter {okayChars.contains($0) })
}
func addCharacters(text: String) -> String{
//print(text.characters.count)
if text.characters.count <= digitsAfterComma{
return text
}else if text.characters.count <= digitsAfterComma + 3{
var finalText = text
finalText.insert(",", atIndex: finalText.endIndex.advancedBy(-digitsAfterComma))
return finalText
}else{
var finalText = text
var dots = 0
finalText.insert(",", atIndex: finalText.endIndex.advancedBy(-digitsAfterComma))
for i in (digitsAfterComma+3)...text.characters.count{
if i%3 == 0{
finalText.insert(".", atIndex: finalText.endIndex.advancedBy(-i - dots))
dots += 1
}
}
return finalText
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.