给定文本中将以给定大小显示多少部分

时间:2012-10-26 12:19:15

标签: ios nsstring drawing uilabel cgrect

获取视图中显示的NSString部分。

或者

获取可在给定CGRect中显示的NSString。

它返回视图上显示的字符串(UIlabel,UITextFiled等)。 当字符串到大并且视图不够长以显示整个字符串时,这很有用。

所以我编写了代码并在此处添加了它。

1 个答案:

答案 0 :(得分:0)

//If you want the string displayed in any given rect, use the following code..
@implementation NSString (displayedString)

//font- font of the text to be displayed
//size - Size in which we are displaying the text

-(NSString *) displayedString:(CGSize)size font:(UIFont *)font
{
NSString *written = @"";

int i = 0;
int currentWidth = 0;
NSString *nextSetOfString = @"";

while (1)
{
    NSRange range;
    range.location = i;
    range.length = 1;

    NSString *nextChar = [self substringWithRange:range];
    nextSetOfString = [nextSetOfString stringByAppendingString:nextChar];

    CGSize requiredSize = [nextSetOfString sizeWithFont:font constrainedToSize:CGSizeMake(NSIntegerMax, NSIntegerMax)];
    currentWidth = requiredSize.width;

    if(size.width >= currentWidth && size.height >= requiredSize.height)
    {
        written = [written stringByAppendingString:nextChar];
    }
    else
    {
        break;
    }
    i++;
}


    return written;
}

@end