hi everybody. i'm making a program using swift which should support ios7. i want the user to see separated thousands "while typing" numbers in the text field.
for example: 1,234,567 instead of 1234567.
somebody has raised the question below but regarding objective-c. i need a swift code please.
http://stackoverflow.com/questions/5176606/formatting-textfield-while-user-is-typing
in case anyone needs the answer in future the structure should be like this:
/
/
/
/
/
/
/
import Foundation
class CostofHearingController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField! //outlet for textField
@IBOutlet weak var formattedLabel: UILabel! //outlet for a label you create as a background for textfield
var formatter : NSNumberFormatter!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
/
}
func textField(aTextField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var textFieldValue: String = aTextField.text!.stringByAppendingString(string)
if range.length > 0 {
textFieldValue = aTextField.text!.substringToIndex(range.location)
}
if (textFieldValue == "") {
self.formattedLabel.text = textFieldValue
}
else {
let newValue: NSDecimalNumber = NSDecimalNumber(string: textFieldValue)
if (formatter == nil) {
formatter = NSNumberFormatter()
}
formatter.numberStyle = .DecimalStyle
self.formattedLabel.text = formatter.stringFromNumber(newValue)
}
return true
}
}
//add this extention after the class
extension String {
func substringToIndex(index: Int) -> String {
if (index < 0 || index > self.characters.count) {
return ""
}
return self.substringToIndex(self.startIndex.advancedBy(index))
}
}