UILabel does not pass text after assigning NSAttributedString

I have a label with a limited width, and I need it to automatically adjust the font size for the text. Since I need to underline the text, I assigned this label to the attribute:

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

As you can see, the number of comments will determine the length of the text. But for some reason the text is not shortened. The minimum font scale is set to 0.1 and the "Tighten the distance between letters" checkbox is selected.

I thought this might refer to the custom font that I use, but even with a standard system font, the text will be cropped.

+4
source share
2 answers

label

@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;
    }

+5

Strings (-) . .

, , 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
    }
}
0

All Articles