Autoshrink on a UILabel with multiple lines

前端 未结 17 2014
醉梦人生
醉梦人生 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 22:21

    I modified the above code somewhat to make it a category on UILabel:

    Header file:

    #import 
    @interface UILabel (MultiLineAutoSize)
        - (void)adjustFontSizeToFit;
    @end
    

    And the implementation file:

    @implementation UILabel (MultiLineAutoSize)
    
    - (void)adjustFontSizeToFit
    {
        UIFont *font = self.font;
        CGSize size = self.frame.size;
    
        for (CGFloat maxSize = self.font.pointSize; maxSize >= self.minimumFontSize; maxSize -= 1.f)
        {
            font = [font fontWithSize:maxSize];
            CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
            CGSize labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
            if(labelSize.height <= size.height)
            {
                self.font = font;
                [self setNeedsLayout];
                break;
            }
        }
        // set the font to the minimum size anyway
        self.font = font;
        [self setNeedsLayout];
    }
    
    @end
    

提交回复
热议问题