2019-01-24

2019-01-24  本文已影响2人  SMFly
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
  }
上一篇下一篇

猜你喜欢

热点阅读