写在前面:
最近遇到这样一个需求, Label 的宽度是一定的, 内容是后台返回的(可能有中文,英文,标点等等), 显示不下直接截断,不显示省略号
前期做的一下常识:
之前有试过Label 的自带属性lineBreakMode, 但是发现8.0之后文字会被截成两半, 针对这个问题确实没找到什么特别好的解决方案, 于是就有了今天的这一篇.
解决方案:
经过一系列的常识没解决之后, 遍决定自己写一个方案来解决.
首先要解决的就是区分中英文:可以通过正则表达式,或者ASCII码都可以实现, 但是相比来说的话, ASCII码判断更好一些
/*验证输入文字是否为中文*/
- (BOOL)isValidateChineseStr:(NSString *)text
{
int asciiCode = [text characterAtIndex:0];
if (asciiCode > 47 && asciiCode < 58) {//数字
return NO;
}
if (asciiCode > 64 && asciiCode < 91) {//大写字母
return NO;
}
if (asciiCode > 96 && asciiCode < 123) {//小写
return NO;
}
//以下为正则表达式
NSString *phoneRegex = @"[\u4e00-\u9fa5]";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
return [phoneTest evaluateWithObject:text];
}
/**
* 限制产品名称字数
*
* @param length 要求长度(字节数)
*/
+ (NSString *)changeProductNameWithProductName:(NSString *)productName length:(NSInteger)length
{
if (productName.length < length/2) return productName;
NSString * name = [NSString string];
NSString * temp = nil;
NSInteger count = productName.length > length ? length : productName.length;
int j = 0;
for (int i = 0; i < count; i ++) {
temp = [productName substringWithRange:NSMakeRange(i, 1)];
j++;
BOOL isChinese = [self isValidateChineseStr:temp];
if (isChinese) {
j ++;
if (i >= count) {
break;
}
}
if (j >= length) {
break;
}
name = [NSString stringWithFormat:@"%@%@",name,temp];
}
return name;
}
这样就实现了 限制宽度显示文字了,