我用过的代码限制在我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使用逗号。 那么我怎样才能解决这个问题,阻止它们呢?
答案 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
}