William Lloyd William Lloyd - 9 days ago 4
Swift Question

Change textfield dynamically and label to currency

New to swift, I built a simple app with a texfield, a button and a label. I want to be able to enter a number into the textfield and have it dynamically change to a currency, i.e. 1200 changes to $1,200.00. Then when I push my button I want to have that currency multiply with a constant say 2 and display the currency amount in the label as it did in the textfield. I can't seem to get this currency converter to work in Swift 3. My code is pretty simplistic so I have not really showed anything here just looking for a way to format the textfield and label answer.

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

@IBOutlet var Picker1: UIPickerView!
var Array = ["1", "2"]

@IBOutlet var grossSalary: UITextField!

@IBOutlet var text: UILabel!

var mult = 2


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Picker1.delegate = self
Picker1.dataSource = self
grossSalary.delegate = self
grossSalary.keyboardType = UIKeyboardType.numbersAndPunctuation
text.text = ""

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Array[row]
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array.count
}

func numberOfComponents(in pickerView: UIPickerView) -> Int{
return 1
}



@objc(textField:shouldChangeCharactersInRange:replacementString:) func textField(_ grossSalary: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789.").inverted
return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
grossSalary.resignFirstResponder()
return true
}

@IBAction func changetext(_ sender: AnyObject) {
text.text = grossSalary.text
// let result = (text.text.toInt() ?? 0) * 2
// text.text = "\(result)"

let a = grossSalary.text
let b = Int(a!)! * mult

text.text = ("$\(b)0")



}


}

Answer

Used Number Formatter() to achieve result.

//dynamically change to currency text for cash down payment
func myTextFieldDidChange1(_ textField: UITextField) {

    if let amountString1 = cdptext.text?.currencyInputFormatting() {
        cdptext.text = amountString1
    }
}

extension String {

// formatting text for currency textField
func currencyInputFormatting() -> String {

    var number: NSNumber!
    let formatter = NumberFormatter()
    formatter.numberStyle = .currencyAccounting
    formatter.currencySymbol = "$"
    formatter.maximumFractionDigits = 2
    formatter.minimumFractionDigits = 2

    var amountWithPrefix = self

    // remove from String: "$", ".", ","
    let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
    amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")

    let double = (amountWithPrefix as NSString).doubleValue
    number = NSNumber(value: (double / 100))

    // if first number is 0 or all numbers were deleted
    guard number != 0 as NSNumber else {
        return ""
    }

    return formatter.string(from: number)!
}

}