美文网首页
银行卡号输入格式化-swift

银行卡号输入格式化-swift

作者: 夏天爱大树 | 来源:发表于2016-08-08 10:48 被阅读407次
     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
            }
            
        }
    
    

    相关文章

      网友评论

          本文标题:银行卡号输入格式化-swift

          本文链接:https://www.haomeiwen.com/subject/gcqrsttx.html