0

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

或者

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

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

所以我已经编写了代码并将其添加到这里。

4

1 回答 1

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
于 2012-10-26T12:19:48.550 回答