Swift控制UITextField最多输入2位小数
2016-06-25 本文已影响576人
蛊惑佬
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let futureString: NSMutableString = NSMutableString(string: textField.text!)
futureString.insertString(string, atIndex: range.location)
var flag = 0;
let limited = 2;//小数点后需要限制的个数
if !futureString.isEqualToString("") {
for i in (futureString.length - 1).stride(through: 0, by: -1) {
let char = Character(UnicodeScalar(futureString.characterAtIndex(i)))
if char == "." {
if flag > limited {
return false
}
break
}
flag += 1
}
}
return true
}