我有一个文本数组,其中包含粗体部分。这个粗体字或句子的位置没有规则,所以我使用webView在必要的地方显示带有粗体标记的html字符串。现在我的webViews不会滚动到任何地方,有时文本也不适合它们。
所以我的问题是:
我想裁剪文本,使其适合我的webView,并且裁剪不会在句子中间,而是在不适合的情况下裁剪整个句子。所以最后,文本应该以合适的最后一句结束。
我所做的是从html句子中去除html标签,计算文本所占的高度,然后删除文本的最后一部分,用"分隔"(点)如果超过要求的高度。
这是执行此操作的代码。
NSString*returnedString=[[NSStringalloc]initWithString:htmlText]autorelease];
CGSize a = [[returnedString stripHtml] sizeWithFont:font constrainedToSize:CGSizeMake(sizeToFit.width, 999)];
NSMutableArray *sentences = [[NSMutableArray alloc] initWithArray:[returnedString componentsSeparatedByString:@"."]];
while (a.height > sizeToFit.height) {
_lastTextExceededLimits = NO;
if (sentences.count > 1) {
// -2 because last sentence is not deletable and contains html tags
NSString *sentence2 = [sentences objectAtIndex:(sentences.count - 2)];
NSString *stringToReplace = [NSString stringWithFormat:@"%@%@",sentence2, @"."];
returnedString = [returnedString stringByReplacingOccurrencesOfString:stringToReplace withString:@""];
[sentences removeLastObject];
} else
returnedString = [returnedString stringByReplacingOccurrencesOfString:[sentences lastObject] withString:@""];
a = [[returnedString stripHtml] sizeWithFont:font constrainedToSize:CGSizeMake(sizeToFit.width, CGFLOAT_MAX)];
}
[sentences release];
return returnedString;