func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var text = textField.text! as NSString
//设置格式为数字
let characterSet = NSCharacterSet(charactersInString: "0123456789")
//去掉空格
let str = string.stringByReplacingOccurrencesOfString(" ", withString: "")
let nsStr = str as NSString
if nsStr.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound {
return false
}
//将输入的数字添加给textfield
text = text.stringByReplacingCharactersInRange(range, withString: string)
//去掉空格
text = text.stringByReplacingOccurrencesOfString(" ", withString: "")
var newString = ""
while text.length > 0 {
let substring = text.substringToIndex(getMin(text.length, num2: 4))
newString = newString.stringByAppendingString(substring)
if substring.characters.count == 4 {
newString = newString.stringByAppendingString(" ")
}
text = text.substringFromIndex(getMin(text.length, num2: 4))
}
newString = newString.stringByTrimmingCharactersInSet(characterSet.invertedSet)
if newString.characters.count >= 20 { //设置银行卡位数为16
return false
}
numberTextField.text = newString
return false
}
func getMin(num1 : Int, num2: Int) -> Int {
if num1 <= num2 {
return num1
}else{
return num2
}
}
网友评论