手动格式化

时间:2017-07-11 14:10:25

标签: ios swift

当我打字的时候,请把Swift中的新手帮帮我。或者在.0或.00之后它应该用0.00反映,但这对于myTxtField.text是不可见的。

以下是我的代码 -

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        // return NO to not change text
        //Decimal
      switch string {
      case "0","1","2","3","4","5","6","7","8","9",".":
            currentString += string
            print(currentString)
            formatCurrency(currentString)

      default:
            if string.characters.count == 0 && currentString.characters.count != 0 {
                currentString = String(currentString.characters.dropLast())
                formatCurrency(currentString)
         }
     }

     return false 
}

func formatCurrency(string: String) {

      let formatter = NSNumberFormatter()
      formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
      formatter.maximumFractionDigits = 2
      formatter.roundingMode = .RoundDown
      formatter.locale = NSLocale(localeIdentifier: "en_US")
      let numberFromField = (NSString(string: currentString).doubleValue)
      let tAmount:String!
      if string == "" {
         myTxtField.text = ""
         tAmount = "$" + formatter.stringFromNumber(numberFromField)!
      }else {
         myTxtField.text = "$" + formatter.stringFromNumber(numberFromField)!
         tAmount = "$" + formatter.stringFromNumber(numberFromField)!
      }
      print("value=\(HManager.convertCurrencyToDouble(tAmount))")

}

1 个答案:

答案 0 :(得分:1)

以下是使用shouldChangeCharactersIn委托方法和editingDidEnd来实现目标的示例。

  • shouldChangeCharactersIn将文本字段限制为仅接受数字和小数点.
  • editingDidEnd是使用2位十进制数字格式化文本字段。

enter image description here

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let allowedCharacters = CharacterSet.decimalDigits

        if string.rangeOfCharacter(from: allowedCharacters.inverted) != nil {
            // If the added character is not a number
            if string == "." {
                // If the added character is the decimal point
                let countDots = textField.text!.components(separatedBy: ".").count - 1
                if countDots == 0 {
                    return true
                }
            }
            return false
        }
        return true
    }

    @IBAction func editingDidEnd(_ sender: UITextField) {
        // Format the input with 2 decimal digits.
        if let input = sender.text, let inputDouble = Double(input) {
            sender.text = String(format: "%.2f", inputDouble)
        } else {
            sender.text = "0.00"
        }
    }
}

<强>更新

为了添加货币符号($)并根据需要删除小数部分,您需要有一个函数来检查输入是double还是Int

@IBAction func editingDidEnd(_ sender: UITextField) {
    // Format the input with 2 decimal digits.
    if let input = sender.text, let number = Double(input) {
        if canConvertToInt(number) {
            sender.text = "$\(Int(number))"
        } else {
            sender.text = "$\(number)"
        }
    } else {
        sender.text = "$0"
    }
}

// Check if the number is not decimal
func canConvertToInt(_ double: Double) -> Bool {
    return rint(double) == double
}