Optimization 在IOS中有效地确定UILabel中可以容纳多少文本

Optimization 在IOS中有效地确定UILabel中可以容纳多少文本,optimization,nsstring,uilabel,Optimization,Nsstring,Uilabel,我有一个NSString,我想知道有多少字符串可以放入UILabel 我的代码通过从原始字符串中一次添加一个字符来构建测试字符串。每次添加字符时,我都会测试新字符串,看它是否适合我的标签: CGRect cutTextRect = [cutText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil];

我有一个NSString,我想知道有多少字符串可以放入UILabel

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

CGRect cutTextRect = [cutText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil];
然后将该矩形的高度与标签的高度进行比较,以查看字符串是否溢出

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

有人能想出或知道一种更快的方法来做到这一点吗


谢谢

虽然不是最漂亮的:

- (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更好的起点。 我愿意接受有关这方面的建议

-编辑:

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

换句话说,获取“文本宽度”是一个棘手的部分,“文本宽度”是我们免费获得的