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

标签 ios uilabel nsattributedstring shrink

我有一个宽度有限的标签,我需要它来自动调整字体大小以适应文本。 因为我需要给文本加下划线,所以我为这个标签分配了一个属性字符串:

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

如您所见,评论的数量将决定文本的长度。但由于某种原因,文本并没有缩小。最小字体比例设置为 0.1 并选中收紧字母间距。

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

最佳答案

我会尝试设置标签属性

@property(nonatomic) BOOL adjustsFontSizeToFitWidth

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

这是我当时用来手动更改字体大小的代码。我不确定你的问题是什么,但这最终很好地解决了我的问题。只需在设置标签文本时调用此方法,然后自行设置字体大小即可。

    - (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

关于ios - 分配 NSAttributedString 后,UILabel 不会自动收缩文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21263847/

相关文章:

ios - swift : View's frame getting altered when a subview is added

ios - UILabel 无法正确显示文本

objective-c - UIImageView 中的 UILabel 文本被截断

objective-c - UIButton setAttributedTitle : forState: Not Showing Up

ios - 如何针对特定目标文件大小优化图像大小?

ios - Podspec 验证但未安装文件

objective-c - objective c - HTML 到 NSAttributedString

ios - 如何在iOS的NSAttributedString中设置属性?

ios - 使用触摸滚动 SpriteNode

ios - 水平堆栈 View 内的标签宽度相等?