iOS字符截取(表情汉字)

TextField、TextView 输入,超过设定长度自动截取符合规定长度。一个汉字相当于两个字符。添加一个类别,实现如下:

//字符长度限制
- (BOOL)stringLengthValidateWithLimitLength:(NSInteger)maxLength{
    
    BOOL result = YES;
    if ([self countOfBytes] > maxLength)
        result = NO;
    return  result;
    
}

- (NSInteger)countOfBytes {
    
    return [self dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)].length;
    
}

- (NSString *)substringWithLength:(NSInteger)maxLength{
    
    __block NSInteger leng = 0;
    __block NSString *result = nil;
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length)
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop)
    {
        leng += [substring dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)].length;
        if (leng >= maxLength) {
            result = [self substringWithRange:NSMakeRange(0, enclosingRange.location + enclosingRange.length)];
            *stop = YES;
        }
        
    }];
    return result;
    
}

 

posted on 2016-03-31 10:55  期待、  阅读(365)  评论(0编辑  收藏  举报

导航