//计算总共字数和限制字数的Index位置 -(NSMutableArray *) unicodeLengthOfString: (NSString *) text { NSMutableArray *array = [NSMutableArray array]; float asciiLength = 0; NSInteger maxmumShowIndex = 0; for (NSUInteger i = 0; i < text.length; i++) { unichar uc = [text characterAtIndex: i]; if (isalnum(uc)) { asciiLength += 1.1; }else{ asciiLength += isascii(uc) ? 1 : 2; } //计算可以显示的最大字数的Index位置 if (asciiLength /2 < _maxMumCharactors) { maxmumShowIndex =i; } } //所有的字数 NSUInteger unicodeLength = asciiLength / 2; if((NSInteger)asciiLength % 2) { unicodeLength++; } [array addObject:[NSNumber numberWithInteger:unicodeLength]]; [array addObject:[NSNumber numberWithInteger:maxmumShowIndex]]; return array; }
代码解释: 设中文字数宽度为2, 非中文(isascii)宽度为1, 数字宽度为1.
所有宽度之和为R, 所有字数之和为 H, H = R / 2 + R%2,
上面的代码只是在计算刚刚超过限制字数时的Index位置。然后再截取或替换超过部分字符串。
NSArray *titleTextLengthArray = [self unicodeLengthOfString:self.titleString]; if ([[titleTextLengthArray firstObject] integerValue] >_maxMumCharactors) { NSInteger maxMumLength = [[titleTextLengthArray lastObject] integerValue]; self.titleString = [self.titleString stringByReplacingCharactersInRange:NSMakeRange(maxMumLength, self.titleString.length-maxMumLength) withString:@"..."]; }
另外经过研究:self.titleString.length 其实是字符的个数。stringByReplacingCharactersInRange 这个方法也是针对字符数。
unichar uc = [text characterAtIndex: i]; 这个方法取的是具体的第几个字符。