计算适合UILabel的子字符串

时间:2017-04-24 14:59:20

标签: ios objective-c uilabel

我有一个UILabel在某些情况下需要是正方形,UILabel中的文字可能不一定适合广场UILabel,因此我需要计算适合UILabel框架的文本数量。我正在使用这段代码来获取字符串的索引,该子字符串适合UILabel -

CGFloat labelWidth     = self.textLabel.frame.size.width;
CGFloat labelHeight    = self.textLabel.frame.size.height - titleRect.size.height - 16.0;
CGSize  sizeConstraint = CGSizeMake(labelWidth, CGFLOAT_MAX);

NSDictionary *attributes = @{ NSFontAttributeName : font};

CGRect boundingRect = [body boundingRectWithSize:sizeConstraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
if (boundingRect.size.height > labelHeight)
{
    NSUInteger stringIndex = 0;
    NSUInteger prev;
    NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    do
    {
        prev = stringIndex;
        if (mode == NSLineBreakByCharWrapping)
            stringIndex++;
        else
            stringIndex = [body rangeOfCharacterFromSet:characterSet options:0 range:NSMakeRange(stringIndex + 1, [body length] - stringIndex - 1)].location;
    }

    while (stringIndex != NSNotFound && stringIndex < [body length] && [[body substringToIndex:stringIndex] boundingRectWithSize:sizeConstraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil].size.height <= labelHeight);

    return prev;
}

我使用这个索引得到的子字符串太大了,超出了UILabel的框架

我做错了什么?

编辑

我正在尝试按@rmaddy的建议使用NSLineBreakByTruncatingTail,但UILabel内的UIScrollView拒绝坚持它的框架。这是代码 -

self.textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x, self.textLabel.frame.origin.y, self.textLabel.frame.size.width, self.textLabel.frame.size.width);
[self setText:self.titleText andBody:self.bodyText andFontName:fontname andSize:size andColor:self.color];

我想设置UILabel中的文字正在调整它的高度。我在设置框架之前尝试过设置文本,但它也不起作用。我现在已经被困在这里太久了。

1 个答案:

答案 0 :(得分:0)

您可以做的是检查字符串的长度并使其适应标签宽度。

这样的事情:

CGSize sizeOfText = [self.label.text boundingRectWithSize: CGSizeMake(self.label.intrinsicContentSize.width, CGFLOAT_MAX)
                                             options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes: [NSDictionary dictionaryWithObject:self.label.font forKey:NSFontAttributeName] context: nil].size;

if (self.label.intrinsicContentSize.height < ceilf(sizeOfText.height)) {
// label is truncated
// so do something here
}else{
// in here do something else
}