美文网首页
iOS 完美解决UITextField输入长度限制 如 12个字

iOS 完美解决UITextField输入长度限制 如 12个字

作者: 繁华乱世沧桑了谁的容颜 | 来源:发表于2019-05-15 11:12 被阅读0次

设置一个汉字等于几个英文字母

  -(NSUInteger)textLength: (NSString *) text{

    NSUInteger asciiLength = 0;

      for (NSUInteger i = 0; i < text.length; i++) {
    
    
        unichar uc = [text characterAtIndex: i];
    
            //设置汉字和字母的比例  如何限制4个字符或12个字母 就是1:3  如果限制是6个汉字或12个字符 就是 1:2  一次类推
        asciiLength += isascii(uc) ? 1 : 3;
    }

    NSUInteger unicodeLength = asciiLength;

    return unicodeLength;

  }

打开textfield的代理 判断字符长度以确定是否需要加入

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSInteger length = [self textLength:newString];//转换过的长度
    NSLog(@"%@------长度: %ld",newString,length);

    if (length > 12)
    {
        return NO;
    }

    return YES;
}

相关文章

网友评论

      本文标题:iOS 完美解决UITextField输入长度限制 如 12个字

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