Autoshrink on a UILabel with multiple lines

前端 未结 17 2057
醉梦人生
醉梦人生 2020-11-28 21:31

Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel? for example, the large text size possible on 2 available lines.

17条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 21:56

    i liked DaGaMs's answer, but in using labels like in UITableViewCells that could be returned of dequeueReusableCell:, the regular font size would continue to shrink even as the original font size was still desired for some tableView cells that had less text and could take advantage of the original label's original font size.

    so, i starting with DaGaMs's category as a jumping off point, i created a separate class rather than a separate category, and i make sure my UILabels in my storyboard make use of this new class:

    #import "MultiLineAutoShrinkLabel.h"
    
    @interface MultiLineAutoShrinkLabel ()
    @property (readonly, nonatomic) UIFont* originalFont;
    @end
    
    @implementation MultiLineAutoShrinkLabel
    
    @synthesize originalFont = _originalFont;
    
    - (UIFont*)originalFont { return _originalFont ? _originalFont : (_originalFont = self.font); }
    
    - (void)quoteAutoshrinkUnquote
    {
        UIFont* font = self.originalFont;
        CGSize frameSize = self.frame.size;
    
        CGFloat testFontSize = _originalFont.pointSize;
        for (; testFontSize >= self.minimumFontSize; testFontSize -= 0.5)
        {
            CGSize constraintSize = CGSizeMake(frameSize.width, MAXFLOAT);
            CGSize testFrameSize = [self.text sizeWithFont:(font = [font fontWithSize:testFontSize])
                                         constrainedToSize:constraintSize
                                             lineBreakMode:self.lineBreakMode];
            // the ratio of testFontSize to original font-size sort of accounts for number of lines
            if (testFrameSize.height <= frameSize.height * (testFontSize/_originalFont.pointSize))
                break;
        }
    
        self.font = font;
        [self setNeedsLayout];
    }
    
    @end
    

提交回复
热议问题