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

时间:2016-10-29 05:32:12

标签: swift button textfield currency numberformatter

swift的新手,我用texfield,按钮和标签构建了一个简单的应用程序。我希望能够在文本字段中输入一个数字,并将其动态更改为货币,即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")



}

}

2 个答案:

答案 0 :(得分:1)

使用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)!
  }
}

答案 1 :(得分:0)

您可以使用:

let balance = 125.78

let balanceCurrency = balance.currency

lblBalance.text = balanceCurrency

返回$ 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) ?? ""
    }

}