分配NSAttributedString后,UILabel不会自动收缩文本

时间:2014-01-21 16:32:37

标签: ios uilabel nsattributedstring shrink

我有一个宽度有限的标签,我需要它来自动调整文字的字体大小以适应。 由于我需要加下划线的文字,因此我为此标签指定了一个属性字符串:

[_commentsLabel setAttributedText:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d comments", [comments count]] attributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)}]];

如您所见,注释的数量将定义文本的长度。但出于某种原因,文本并没有缩小。最小字体比例设置为0.1并选中Tighten Letter Spacing。

我认为它可能与我使用的自定义字体有关,但即使使用系统默认字体,文字也会被剪裁。

3 个答案:

答案 0 :(得分:5)

我会尝试设置标签属性

@property(nonatomic) BOOL adjustsFontSizeToFitWidth

到YES,看看是否能解决问题。如果没有,请告诉我。我在不同的情况下遇到了问题,但我最终使用了一些代码来手动更改大小。

这是我用来手动更改字体大小的代码。我不知道你的问题是什么,但这最终成为我的问题的一个很好的解决方案。只需在设置标签文本时调用此方法,然后自己设置字体大小。

    - (CGFloat)requiredFontSizeForLabel:(UILabel *)label
{
    if (!label) {
        return kFontSize;
    }
    CGFloat originalFontSize = kFontSize;

    UIFont* font = label.font;
    CGFloat fontSize = originalFontSize;

    BOOL found = NO;
    do
    {
        if( font.pointSize != fontSize )
        {
            font = [font fontWithSize: fontSize];
        }
        if([self wouldThisFont:font workForThisLabel:label])
        {
            found = YES;
            break;
        }

        fontSize -= 0.5;
        if( fontSize < (label.minimumScaleFactor * label.font.pointSize))
        {
            break;
        }

    } while( TRUE );

    return( fontSize );
}

    - (BOOL) wouldThisFont:(UIFont *)testFont workForThisLabel:(UILabel *)testLabel {
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:testFont, NSFontAttributeName, nil];
    NSAttributedString *as = [[NSAttributedString alloc] initWithString:testLabel.text attributes:attributes];
    CGRect bounds = [as boundingRectWithSize:CGSizeMake(CGRectGetWidth(testLabel.frame), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) context:nil];
    BOOL itWorks = [self doesThisSize:bounds.size fitInThisSize:testLabel.bounds.size];
    return itWorks;
}

        - (BOOL)doesThisSize:(CGSize)aa fitInThisSize:(CGSize)bb 
    {
        if ( aa.width > bb.width ) return NO;
        if ( aa.height > bb.height ) return NO;
        return YES;
    }

Source for code found here

答案 1 :(得分:0)

AttributeStrings有自己的字体大小。手动执行此操作。

  

构成属性字符串的所有属性字符串必须具有NSFontAttributeName。

func updateLabelSizeIfNeeded() {
    let maxScale: CGFloat = 0.65
    let bounding = self.label.attributedText!.boundingRectWithSize(CGSizeMake(CGFloat.infinity, CGFloat.infinity), options: [], context: nil)
    if bounding.size.width > self.bounds.size.width*maxScale {
        let scaleFactor = (self.bounds.size.width * maxScale) / bounding.size.width

        label.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor)
    } else {
        label.transform = CGAffineTransformIdentity
    }
}

答案 2 :(得分:0)

我通过循环进行此操作

while TheWidthOfSuperview < MyLabel.intrinsicContentSize.width {

    MyLabel.font = MyLabel.font.withSize(MyLabel.font.pointSize - 1)

}
相关问题