开发者

UILabel visible part of text

开发者 https://www.devze.com 2023-01-23 19:22 出处:网络
Is there a way to get the visible part of text in word wrapped UILabel? I mean exactly the last visible character?

Is there a way to get the visible part of text in word wrapped UILabel? I mean exactly the last visible character?

I'd like to make two labels rounding the image and would like to continue the text which was out of rect for first label on the second one.

I know [NSString sizeWithFont...] but are there somethin开发者_Go百科g reversing like [NSString stringVisibleInRect: withFont:...] ? :-)

Thank you in advance.


You could use a category to extend NSString and create the method you mention

@interface NSString (visibleText)

- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font;

@end

@implementation NSString (visibleText)

- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font
{
    NSString *visibleString = @"";
    for (int i = 1; i <= self.length; i++)
    {
        NSString *testString = [self substringToIndex:i];
        CGSize stringSize = [testString sizeWithFont:font];
        if (stringSize.height > rect.size.height || stringSize.width > rect.size.width)
            break;

        visibleString = testString;
    }
    return visibleString;
}

@end


Here's a O(log n) method with iOS 7 APIs. Only superficially tested, please comment if you find any bugs.

- (NSRange)hp_visibleRange
{
    NSString *text = self.text;
    NSRange visibleRange = NSMakeRange(NSNotFound, 0);
    const NSInteger max = text.length - 1;
    if (max >= 0)
    {
        NSInteger next = max;
        const CGSize labelSize = self.bounds.size;
        const CGSize maxSize = CGSizeMake(labelSize.width, CGFLOAT_MAX);
        NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.lineBreakMode = self.lineBreakMode;
        NSDictionary * attributes = @{NSFontAttributeName:self.font, NSParagraphStyleAttributeName:paragraphStyle};
        NSInteger right;
        NSInteger best = 0;
        do
        {
            right = next;
            NSRange range = NSMakeRange(0, right + 1);
            NSString *substring = [text substringWithRange:range];
            CGSize textSize = [substring boundingRectWithSize:maxSize
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:attributes
                                                      context:nil].size;
            if (textSize.width <= labelSize.width && textSize.height <= labelSize.height)
            {
                visibleRange = range;
                best = right;
                next = right + (max - right) / 2;
            } else if (right > 0)
            {
                next = right - (right - best) / 2;
            }
        } while (next != right);
    }
    return visibleRange;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消