我有几个带小数键盘的文本字段,我想让它们在屏幕上显示$和逗号($ 1,222,000.00)。并且还会更改文本的间距,因为添加逗号时会很拥挤。
for textField in self.numberTextField! as [UITextField] {
textField.keyboardType = .DecimalPad
textField.inputAccessoryView = keyboardToolbar
numberTextField是我的文本字段集合。任何帮助赞赏!非常感谢!
答案 0 :(得分:2)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
var newText = oldText.stringByReplacingCharactersInRange(range, withString: string) as NSString!
var newTextString = String(newText)
let digits = NSCharacterSet.decimalDigitCharacterSet()
var digitText = ""
for c in newTextString.unicodeScalars {
if digits.longCharacterIsMember(c.value) {
digitText.append(c)
}
}
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let numberFromField = (NSString(string: digitText).doubleValue)/100
newText = formatter.stringFromNumber(numberFromField)
textField.text = String(newText)
return false
}