发出限制小数长度

时间:2016-01-05 12:45:47

标签: ios swift textfield

我用过的代码限制在我UITexField的所有{1}}中最多1位小数:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let computationString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)


    let arrayOfSubStrings = computationString.componentsSeparatedByString(",")


    if (arrayOfSubStrings.count == 1 && computationString.characters.count > 2) {

        return false

    } else if arrayOfSubStrings.count == 2 {
        let stringPostDecimal = arrayOfSubStrings[1]

        return stringPostDecimal.characters.count <= 1
    }



    return true
}

但我只知道有两种类型的Decimal Pad:带点和逗号。

例如我的iOS模拟器使用点和我的iPhone使用逗号。 那么我怎样才能解决这个问题,阻止它们呢?

2 个答案:

答案 0 :(得分:0)

方法componentsSeparatedByCharactersInSet可以考虑多个分离字符

let commaDotCharacterSet = NSCharacterSet(charactersInString: ",.")
let arrayOfSubStrings = computationString.componentsSeparatedByCharactersInSet(commaDotCharacterSet)

或包括当前区域设置的小数分隔符

let localeDecimalSeparator = NSLocale.currentLocale().objectForKey(NSLocaleDecimalSeparator) as! String
let commaDotLocaleSeparatorCharacterSet = NSCharacterSet(charactersInString: ",." + localeDecimalSeparator)
let arrayOfSubStrings = computationString.componentsSeparatedByCharactersInSet(commaDotLocaleSeparatorCharacterSet)

答案 1 :(得分:0)

试试这个。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let computationString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    let arrayOfSubStrings = computationString.computationString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ".,"))

    if (arrayOfSubStrings.count == 1 && computationString.characters.count > 2) {
        return false
    } else if arrayOfSubStrings.count == 2 {
        let stringPostDecimal = arrayOfSubStrings[1]
        return stringPostDecimal.characters.count <= 1
    }

    return true
}