美文网首页
iOS UITextField限制限制字符串长度

iOS UITextField限制限制字符串长度

作者: _Waiting_ | 来源:发表于2018-05-09 18:20 被阅读26次

    简单说明:
    UITextField限制限制字符串长度:例如要求字符串长度为11位,则textField.text.length > 10
    代码如下:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if (textField == self.userName) {
            if (textField.text.length > 10 && string.length > 0) return NO;
        }
        
        return YES;
    }
    

    Swift

      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
      
                let proposeLength = (textField.text?.lengthOfBytes(using: String.Encoding.utf8))! - range.length + string.lengthOfBytes(using: String.Encoding.utf8)
                if proposeLength > 20 { return false }
    
            return true
            
        }
    

    UITextField限制限制字符串对应的int数值:例如要求字符串>100

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
    
        if (string.length == 0)
        {
            
        }
        else
        {
            if ([textField.text integerValue] * 10 + [string integerValue]>100)
            {
                return NO;
            }
            
        }
        return YES;
    }
    

    相关文章

      网友评论

          本文标题:iOS UITextField限制限制字符串长度

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