动态更改文本字段并将标签更改为货币

Change textfield dynamically and label to currency

swift 的新手,我构建了一个带有文本域、按钮和标签的简单应用程序。我希望能够在文本字段中输入一个数字并将其动态更改为一种货币,即 1200 更改为 $1,200.00。然后,当我按下我的按钮时,我想让该货币乘以一个常数,比如 2,并像在文本字段中那样在标签中显示货币金额。我似乎无法让这个货币转换器在 Swift 3 中工作。我的代码非常简单,所以我在这里没有真正展示任何东西,只是在寻找一种格式化文本字段和标签答案的方法。

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



}

}

已使用 Number Formatter() 取得成果。

//dynamically change to currency formatted 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)!
  }
}

你可以使用这个:

let balance = 125.78

let balanceCurrency = balance.currency

lblBalance.text = balanceCurrency

这 return 0.00 美元

extension NumberFormatter {
    convenience init(style: Style) {
        self.init()
        numberStyle = style
    }
}

extension Formatter {

    static let currency = NumberFormatter(style: .currency)

}

extension FloatingPoint {

    var currency: String {
        return Formatter.currency.string(for: self) ?? ""
    }

}