我有一個類似的問題,我用了Mike發佈的解決方案。
但是,事實證明,trimToWord
經常給我一些太多的單詞,超出了指定的UILabel大小。我發現,如果我將while循環運算符更改爲> =而不僅僅是>,則它完美運行。
我還添加了幾個ivars(chopIndex
和remainingBody
),我用它來獲取剩餘的字符串,以便在下一個UILabel中顯示它。
這是我使用的解決方案。
-(NSString*) rewindOneWord:(NSString*) str{
// rewind by one word
NSRange lastspace = [str rangeOfString:@" " options:NSBackwardsSearch];
if (lastspace.location != NSNotFound){
int amount = [str length]-lastspace.location;
chopIndex -= amount;
return [str substringToIndex:lastspace.location];
}else {
// no spaces, lets just rewind 2 characters at a time
chopIndex -= 2;
return [str substringToIndex:[str length]-2];
}
}
// returns only how much text it could render with the given stipulations
-(NSString*) trimToWord:(NSString*)str sizeConstraints:(CGSize)availableSize withFont:(UIFont*)font{
if(str == @"")
return str;
CGSize measured = [str sizeWithFont:font constrainedToSize:CGSizeMake(availableSize.width, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
// 'guess' how much we will need to cut to save on processing time
float choppedPercent = (((double)availableSize.height)/((double)measured.height));
if(choppedPercent >= 1.0){
//entire string can fit in availableSize
remainingBody = @"";
return str;
}
chopIndex = choppedPercent*((double)[str length]);
str = [str substringToIndex:chopIndex];
// rewind to the beginning of the word in case we are in the middle of one
do{
str = [self rewindOneWord:str];
measured = [str sizeWithFont:font constrainedToSize:availableSize lineBreakMode:UILineBreakModeWordWrap];
}while(measured.height>=availableSize.height);
//increment past the last space in the chopIndex
chopIndex++;
//update the remaining string
remainingBody = [remainingBody substringFromIndex:chopIndex];
return str;
}
不錯的工作teradyl – 2011-04-26 23:57:20
我已經爲您解決了這個問題的答案,因爲您已經改進了我的解決方案。謝謝@teradyl – 2013-05-15 01:52:08