以下是我的代码 -
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))")
}
答案 0 :(得分:1)
以下是使用shouldChangeCharactersIn
委托方法和editingDidEnd
来实现目标的示例。
shouldChangeCharactersIn
将文本字段限制为仅接受数字和小数点.
。 editingDidEnd
是使用2位十进制数字格式化文本字段。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
}