美文网首页
2019-01-24

2019-01-24

作者: SMFly | 来源:发表于2019-01-24 17:06 被阅读2次
    extension LoginViewController:UITextFieldDelegate {
    
    /**
     * 问题:
     * 1.目前没有限制手机号输入时位数(11位),只在最后做校验
     * 2.从手机通讯录复制的手机号存在前缀编码和后缀编码,导致手机号校验失败
     * 
     */
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.count == 0 {
            return true
        }else {
            if let text = textField.text {
                let textLength = text.count
                let finalString = string.getNumber()
                let finalStringLength = finalString.count
                
                if finalStringLength == 0 {
                    return false
                }
                
                if textLength < phoneLimit {
                    let spaceLength = phoneLimit - textLength
                    if finalStringLength > spaceLength {
                        textField.text = text + finalString.prefix(spaceLength)
                        return false
                    }else {
                        textField.text = text + finalString
                        return false
                    }
                }
                
                return false
            }
        }
        return true
    }
    
    }
    
    func getNumber() -> String {
        
        let chartSet = CharacterSet(charactersIn: "0123456789").inverted
        
        let string = self.components(separatedBy: chartSet).joined(separator: "")
        
        return string
      }

    相关文章

      网友评论

          本文标题:2019-01-24

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