UITextField字数限制[中文按2个字符算, Emoji按4个字符算]

1, 使用NSNotification监控变化:

[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textFieldDidChanged:)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:nil];

 2,文本变化事件回调:

- (void)textFieldDidChanged:(NSNotification *)notification
{
    if (_wordsMaxCount > 0) {
        UITextField *textField = _input_text_textField;
        
        NSString *toBeString = textField.text;
        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
        if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
            if (!position || !selectedRange) {
                // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
                textField.text = [self getString:toBeString withCountLimit:_wordsMaxCount];
            } else {
                // 有高亮选择的字符串,则暂不对文字进行统计和限制
            }
        } else {
            // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
            textField.text = [self getString:toBeString withCountLimit:_wordsMaxCount];
        }
    }
}

 3, 字符串截取函数:

- (NSString *)getString:(NSString *)toBeString withCountLimit:(NSInteger)limit
{
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *toBeStringData = [toBeString dataUsingEncoding:encoding];
    NSInteger dataLength = [toBeStringData length];
    if (dataLength > limit) {
        NSString *limitString = nil;
        while (!limitString) {
            limitString = [[NSString alloc] initWithData:[toBeStringData subdataWithRange:NSMakeRange(0, limit)] encoding:encoding];
            limit --;
            
            if (limit <= 0)
                break;
        }
        
        return limitString;
    }

    return toBeString;
}

 4,移除Notification监控

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UITextFieldTextDidChangeNotification
                                                  object:nil];

 

你可能感兴趣的:(IOS开发之旅)