UILabel文本的可见部分

时间:2010-11-04 19:22:51

标签: iphone uilabel

有没有办法在单词包装UILabel中获取文本的可见部分?我的意思是最后一个可见的角色?

我想在图像上制作两个标签,并希望在第二个标签上继续使用矩形作为第一个标签。

我知道[NSString sizeWithFont...]但有些事情像[NSString stringVisibleInRect: withFont:...]那样有所逆转吗? : - )

提前谢谢。

2 个答案:

答案 0 :(得分:7)

您可以使用类别来扩展NSString并创建您提及的方法

@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

答案 1 :(得分:0)

这是使用iOS 7 API的O(log n)方法。只有表面测试,如果您发现任何错误,请发表评论。

- (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;
}