UITextfield中的自动逗号与十进制键盘

时间:2016-07-22 01:29:55

标签: swift swift2 uitextfield

我正在使用具有十进制键盘的UITextField。因此用户只能输入数字。我希望textfield能够自动为每千个用户类型添加逗号。这样用户就可以轻松识别他们输入的内容。有一个共同的方法来做到这一点?

2 个答案:

答案 0 :(得分:4)

here是参考。下面是转换后的swift代码。将委托设置为textField并实现下面的委托方法。

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

    let cs = NSCharacterSet(charactersInString: "0123456789").invertedSet
    let filtered = string.componentsSeparatedByCharactersInSet(cs)
    let component = filtered.joinWithSeparator("")
    let isNumeric = string == component

    // check for input string is numeric value or either a number not a string or character.
    if isNumeric {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        formatter.maximumFractionDigits = 10

        let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
        let numberWithOutCommas = newString.stringByReplacingOccurrencesOfString(",", withString: "")
        let number = formatter.numberFromString(numberWithOutCommas)
        if number != nil {
            let formattedString = formatter.stringFromNumber(number!)
            print(number)
            print(formattedString)
            textField.text = formattedString
        } else {
            textField.text = nil
        }
    }
    return false
}

答案 1 :(得分:1)

This回答应该有所帮助。他们在shouldChangeCharactersInRange方法中添加了逗号。 这是快速等价的

let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let formattedNum = formatter.stringFromNumber(10000000)
textField.text = formattedNum