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

2019-05-15  本文已影响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;
}
上一篇 下一篇

猜你喜欢

热点阅读