Created
August 15, 2016 07:44
-
-
Save yigitserin/306f8f1b0b7dd4d1e25c50078e46a402 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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