2013-07-01 32 views
4

是否有一种简单的方法来拆分NSAttributedString,以便只获取最后50行左右的行?从NSAttributedString中提取最后50行

NSMutableAttributedString *resultString = [receiveView.attributedText mutableCopy]; 
     [resultString appendAttributedString:[ansiEscapeHelper attributedStringWithANSIEscapedString:message]]; 
     if ([[resultString.string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] count]>50) { 
      //resultString = [resultString getLastFiftyLines]; 
     } 
+1

你是问关于线条或字符? ([结果字符串长度]> 50) - 关于字符,而不是行 – Tala

+0

我猜这两个工程,但我更喜欢行。 –

+0

字符串中的行根据字体大小+ UI元素宽度+自动换行来标识。如果有50个字符可用,请不要使其过于复杂,并使用子字符串,如我的回答 – Tala

回答

3

的长度是有一个简单的方法来拆分NSAttributedString,所以我只得到最后50个左右的行?

号你将有权要求string,并确定你有兴趣,然后创建一个使用这样的API从源头上派生的新NSAttributedString表示作为- [NSAttributedString attributedSubstringFromRange:]范围:

- (NSAttributedString *)lastFiftyLinesOfAttributedString:(NSAttributedString *)pInput 
{ 
    NSString * string = pInput.string; 
    NSRange rangeOfInterest = ...determine the last 50 lines in "string"...; 
return [pInput attributedSubstringFromRange:rangeOfInterest]; 
} 
+0

这听起来很辛苦...... 我想我可以从确定最后50行: [resultString.string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]计数] 但我怎么做的NSRange出来的那...... –

+0

@DavidKarlsson使用这个API,你可以将'-componentsSeparatedByCharactersInSet:'返回的最后50个字符串的'-length'加起来,并且为每个换行符加1(被'-componentsSeparatedByCharactersInSet:'省略)。总和是感兴趣的字符串(例如最后的234个字符)的* length *,所以'NSRange'将是'{string.length-sum/* location * /,sum/* length * /}'。 – justin

2

可以使用AttributedString的子方法:

if ([resultString length]>50) { 
    resultString = [resultString attributedSubstringFromRange:NSMakeRange(0, 50)]; 
} 

NSMakeRange - 0告诉我们从哪里开始和50是子

+0

这是最后的50 *字符。*我相信OP正在查找最后50行* –

+0

让我们仔细检查。由于他在他的问题 – Tala

+0

中使用[resultString length]> 50,这不是50个首字符吗?从0到50? –