顯示的效果是:咱們是一個快樂的...(超過必定(例子是8個)數量時,後面的用...代替)服務器
1.第一種狀況字符串的截取。app
//1.字符串設置長度,長度限制----字符串(目的:超過length時,後面顯示...代碼以下) + (NSString *)stringWithHtml:(NSString *)str length:(CGFloat)length{ if (!str) return nil; if (str && [str isKindOfClass:[NSString class]]) { CGFloat character = 0; const char *chars = [str cStringUsingEncoding:NSUTF8StringEncoding]; NSUInteger charLength = length; if (strlen(chars) <= charLength*3 +1) {//1個漢字或中文字符3個字節,1個英文1個字節(NSUTF8StringEncoding只適用於這個方法) return str; } //若是有寬度限制的話,建議用 if(str.length<=length){return str}; //缺點是字母或數字或中文與數字字母混合時計算有誤,還會執行下面方法,但比較保險 //獲取字數(字節數乘以2便可) for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i]; if( a >= 0x4e00 && a <= 0x9fa5){ //判斷是否爲中文 character +=1; }else{ if ((isalpha(a))||(isalnum(a))||isascii(a)) { character+=0.5; }else{ character +=1; } } if (character > length) {//按字數截取 if (character == length) { str = [str substringToIndex:i+1]; }else{ str = [str substringToIndex:i]; } str = [str stringByAppendingString:@"..."]; break; } } } return str; }
2.第二種狀況簡單富文本的截取。spa
//2.NSAttributedString 按照字符數(中文1個字佔1位)量截取 + (NSAttributedString*)subString:(NSAttributedString*)str len:(NSInteger)len{ if (!str) return nil; if (str.length <=len) return str; NSUInteger count = 0; NSMutableAttributedString *sb = [[NSMutableAttributedString alloc]init]; for (int i = 0; i< str.length; i++) { NSRange range = NSMakeRange(i, 1) ; NSAttributedString *aStr = [str attributedSubstringFromRange:range]; count += [aStr.string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]>1?2:1; [sb appendAttributedString:aStr]; if(count >= len*2) {//由於上面已經返回1或2了因此這裏乘以2 if (i == str.length -1) { return sb; }else{ if (sb) { NSMutableAttributedString *temp1 = [[NSMutableAttributedString alloc]initWithAttributedString:sb]; [temp1 appendAttributedString:[[NSAttributedString alloc] initWithString:@"..."]]; return temp1; } } } } return str; }
3.第三種狀況無論是富文本仍是字符串規定用length來判斷長度並截取。blog
NSString *subTitle = @"服務器返回的富文本或字符串" if (subTitle) { NSAttributedString *attribute = [CommonUtil attributedStringWithHtml:subTitle]; if (attribute && [attribute length] > 8) { NSMutableAttributedString *muAttribute = [[NSMutableAttributedString alloc] initWithAttributedString:attribute]; [muAttribute replaceCharactersInRange:NSMakeRange(8,[attribute length]-8) withString:@"..."]; _subLabel.attributedText = muAttribute; }else{ _subLabel.attributedText = attribute; } }