如何在目标c中获得特定高度的字符串

时间:2013-11-22 03:51:46

标签: ios objective-c nsstring

嗨,在我的应用程序中,我有一个很长的字符串。从该字符串开始,我必须将字符串高度为500的字符串的子字符串子串。请告诉我如何获取字符串的一部分。

供我参考,我正在分享用于获取字符串高度的代码

 CGSize finalStringSize = [finalString sizeWithFont:font constrainedToSize:CGSizeMake(195,length) lineBreakMode:NSLineBreakByWordWrapping];

这里的finalstringSize.height是500.现在任何人都可以帮我从最终字符串中获取子字符串,其子字符串高度为500.

请帮帮我。

enter image description here

2 个答案:

答案 0 :(得分:2)

使用此代码设置特定内容高度:

 NSString *finalString=@"d jdsfhksd fsdfhjkds fkdhsfjkdsf kdsfhjkdsf sdjkfsdfh dsfhsfisudi udsifhisdhf sdhfkh sdkf dshf ksdh fkhsd khsdfh sdkhf sdhkfhsdjkfhdshf sdfhdshf hsdfh ksdhf kdhsf hsdkfhsdkhf sdf hsdkfh dsf sdkhf ksdhf hsdfh sdhfksdhf sd ksdhsdh ksdh dhs hsdh ksdh dhs fhsdfh dsfsdfdf sdf sd sd dsf sd fsdf ds"; 
 int length =200; 
 UIFont *font=[UIFont fontWithName:@"Helvetica" size:17.0f]; 
 NSString *firstPartString=[NSString stringWithString:finalString]; 

 CGSize firstPartStringSize = [firstPartString sizeWithFont:font constrainedToSize:CGSizeMake(195,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; 

 while(firstPartStringSize.height > length) 
 { 
      firstPartString = [firstPartString substringWithRange:NSMakeRange(0, firstPartString.length-1)]; 
      firstPartStringSize = [firstPartString sizeWithFont:font constrainedToSize:CGSizeMake(195,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; 
 } 

 if(firstPartStringSize.height <= length) 
 { 
      while(![[firstPartString substringToIndex:[firstPartString length]-1] isEqualToString:@" "]) 
      { 
           NSLog(@"%@",[firstPartString substringFromIndex:[firstPartString length]-1]); 
           if([firstPartString substringFromIndex:[firstPartString length]-1].length !=0 && ![[firstPartString substringFromIndex:[firstPartString length]-1] isEqualToString:@" "]) 
           { 
                firstPartString = [firstPartString substringWithRange:NSMakeRange(0, firstPartString.length-1)]; 
           } 
           else 
           { 
                break; 
           } 

      } 
 } 

 NSString *resultStr=firstPartString; 

 int secondPartStringLength=[finalString length]-firstPartString.length; 
 NSRange secondPartStringRange=NSMakeRange(firstPartString.length, secondPartStringLength); 
 NSString *secondPartString=[finalString substringWithRange:secondPartStringRange];

答案 1 :(得分:0)

根据我的评论,你可以试试这个:

CGSize finalStringSize = [finalString sizeWithFont:font constrainedToSize:CGSizeMake(195,length) lineBreakMode:NSLineBreakByWordWrapping];
while( finalStringSize.height > 500 ){
    finalString = [finalString substringWithRange:NSMakeRange(0, finalString.length-1)];
    finalStringSize = [finalString sizeWithFont:font constrainedToSize:CGSizeMake(195,length) lineBreakMode:NSLineBreakByWordWrapping];
}
NSLog(finalString); // and that is your end string...

根据您在下面的评论,您可以使用CTFramesetterSuggestFrameSizeWithConstraints方法查找NSRange中可以使用的[finalString substringWithRange:range];来获取最终结果。

该方法的文档为here