【问题标题】:Efficiently determine how much text can fit in a UILabel in IOS有效确定IOS中的UILabel可以容纳多少文本
【发布时间】:2015-09-30 16:50:41
【问题描述】:

我有一个 NSString,我想知道该字符串中有多少适合 UILabel。

我的代码通过从我的原始字符串中一次添加一个字符来构建一个测试字符串。每次我添加一个字符时,我都会测试新字符串以查看它是否适合我的标签:

CGRect cutTextRect = [cutText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil];

然后我将该矩形的高度与标签的高度进行比较,以查看字符串是否溢出。

这可行,但仪器显示循环占用了我所有的 cpu 时间。

谁能想到或知道更快的方法来做到这一点?

谢谢!

【问题讨论】:

    标签: optimization nsstring uilabel


    【解决方案1】:

    虽然不是最漂亮的:

    - (NSString *)stringForWidth:(CGFloat)width fullString:(NSString *)fullString
    {
        NSDictionary *attributes = @{NSFontAttributeName: label.font};
    
        if ([fullString sizeWithAttributes:attributes].width <= width)
        {
            return fullString;
        }
    
        // Might be worth researching more regarding 'average' char size 
        CGFloat approxCharWidth = [@"N" sizeWithAttributes:attributes].width;
    
        NSInteger approxNumOfChars = (NSInteger)(width / approxCharWidth);
    
        NSMutableString *resultingString = [NSMutableString stringWithString:[fullString substringToIndex:approxNumOfChars]];
    
        CGFloat currentWidth = [resultingString sizeWithAttributes:attributes].width;
    
        if (currentWidth < width)
        {
            // Try to 'sqeeze' another char.
            while (currentWidth < width && approxNumOfChars < fullString.length)
            {
                approxNumOfChars++;
    
                [resultingString appendString:[fullString substringWithRange:NSMakeRange(approxNumOfChars - 1, 1)]];
    
                currentWidth = [resultingString sizeWithAttributes:attributes].width;
            }
        }
    
        // String might be oversized
        if (currentWidth > width)
        {
            while (currentWidth > width)
            {
                [resultingString deleteCharactersInRange:NSMakeRange(resultingString.length - 1, 1)];
    
                currentWidth = [resultingString sizeWithAttributes:attributes].width;
            }
        }
    
        // If dealing with UILabel, it's safer to have a smaller string than 'equal',
        // 'clipping wise'. Otherwise, just use '<=' or '>=' instead of '<' or '>'
    
        return [NSString stringWithString:resultingString];
    }
    

    有几个循环,但每个循环都是“微调”,应该只运行少量次。

    提高效率的一种方法是获得一个比计算给定宽度可以容纳多少 N 更好的起点。 我愿意接受有关这方面的建议。

    -编辑:

    关于多行标签,一旦我知道给定文本的宽度,我可以预期以下文本(如果有)将转到下一行。

    换句话说,获取 'text for width' 是棘手的部分,'width for text' 我们免费获得。

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 2011-11-16
      • 2011-02-10
      相关资源
      最近更新 更多