计算适合Uilabel的基因



我有一个UILabel,在某些情况下需要是正方形的,而在UILabel中使用的文本可能不一定适合Square 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,但是UIScrollView内部的UILabel拒绝粘在其框架上。这是代码 -

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中的文本正在使其调整其高度。我已经尝试在设置框架之前设置文本,但它也不起作用。我已经陷入了这么长时间。

您能做的就是检查字符串的长度并将其调整为标签宽度。

类似的东西:

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
}

最新更新