separate thousands in textfield

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

Answered by mdehghani in 155494022

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))
    }
}

If you need in swift, just translate from objective C ! 😉


Seriously, what is the specific point of translation that causes you problem ?

I'm new to ios programming and i just know the basics of swift. can this be done using online translators?

Search for "objective-c to swift translator". Maybe you have to do some fixes but it shouldn't be too hard.

you can try with online translator, but it should be easy to do it by yourself.

I am not on XCode presently, so I can just give you hints by translating line line by line, but cannot check it, so I am not completely sure of some syntax. But that should give you an idea.


Start with


var formatter : NSNumberFormatter


Type:

func textField(

Autocompletion should let you find the appropriate method with shouldChangeCharactersInRange, with the parameters aTextField and string


var TextFieldValue = aTextField.text + string

if range.length > 0 {

textFieldValue = aTextField.text.substringToIndex(range.location) // check how substringToImndex must be called

}


if textFieldValue == "" {

self.formattedLabel.text = ""

} else {

let newValue = NSDecimalNumber(textFieldValue)

if formatter == nil {

formatter = NSNumberFormatter()

formatter.numberStyle = NSNumberFormatterDecimalStyle

self.formattedLabel.text = formatter.stringFromNumber(newValue). // check how stringFromNumber must be called

}


return true

}

thank you. this is what i've done so far but still recieve 2 errors in code. which i have commented.


import Foundation
class CostofHearingController: UIViewController, UITextFieldDelegate  {

  @IBOutlet weak var textField: UITextField!

    var formatter : NSNumberFormatter!
  
    @IBOutlet weak var formattedLabel: UILabel!

   override func viewDidLoad() {
        super.viewDidLoad()


    }
  

    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)   //String may not be indexed with 'Int', it has variable size elements
        }
        if (textFieldValue == "") {
            self.formattedLabel.text = textFieldValue
        }
        else {
            var newValue: NSDecimalNumber = NSDecimalNumber(string: textFieldValue)
            if (formatter == nil) {
                formatter = NSNumberFormatter()
            }
            formatter.numberStyle = NSNumberFormatterDecimalStyle     // use of unresolved identifier
            self.formattedLabel.text = formatter.stringFromNumber(newValue)
        }
        return true
    }
  
}

}

For the first, you can add this extension to String so that it accepts Int index extension String { func substringToIndex(index: Int) -> String { if (index < 0 || index > self.characters.count) { print("index \(index) out of bounds") return "" } return self.substringToIndex(self.startIndex.advancedBy(index)) } } For the second, try to add a dot before NSNumberFormatterDecimal or check in the doc how to call it in Swift.

I edit the message which was unreadable as formatted byiPhone.



For the first, you can add this extension to String so that it accepts Int index

extension String {

func substringToIndex(index: Int) -> String {

if (index < 0 || index > self.characters.count) {

// print("index \(index) out of bounds")

return ""

}

return self.substringToIndex(self.startIndex.advancedBy(index))

}

}

For the second, try to add a dot before NSNumberFormatterDecimal or check in the doc how to call it in Swift.

can you please place the extention in the original code? because i don't really know where to put it

You should put it after the class declaration .

i resolved the issues as you mentioned and run the program but no formatting is applyed to the textfield or the labelview. my current code is:

/
/
/
/
/
/
/ 
import Foundation
class CostofHearingController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate  {
    @IBOutlet weak var textField: UITextField!
 
    @IBOutlet var formattedLabel: UILabel!
   

   
    var formatter : NSNumberFormatter!
   
    override func viewDidLoad() {
        super.viewDidLoad()
       
       
      
       
       

    }
   

    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 {
            var newValue: NSDecimalNumber = NSDecimalNumber(string: textFieldValue)
            if (formatter == nil) {
                formatter = NSNumberFormatter()
            }
            formatter.numberStyle = .DecimalStyle     /
            self.formattedLabel.text = formatter.stringFromNumber(newValue)
        }
        return true
    }
   
   

}
extension String {
    func substringToIndex(index: Int) -> String     {
        if (index < 0 || index > self.characters.count)         {
            /
            return ""
        }
        return self.substringToIndex(self.startIndex.advancedBy(index))
    }
}

How are your IBOutlets connected to variables in code ? In which controller ?


To understand what's going on,it would be useful to see the whole code of the project

I've uploaded the project so far . it would be kind if you take a look. there is only one scene containing a textfield.
http://www.mediafire.com/download/x1v8miiqjdoobt9/dadtest.zip

Does the textField func get called ?


Check that you connected the IBOutlet to its delegate (the file's owner)

i uploaded the project and posted the link which is awaiting moderation

Accepted Answer

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))
    }
}
separate thousands in textfield
 
 
Q