Autoshrink on a UILabel with multiple lines

前端 未结 17 2080
醉梦人生
醉梦人生 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:01

    Thank you to DaGaMs for this solution.

    I've updated it as follows:

    1 - To work with iOS 6 (since both minimumFontSize and UILineBreakModeWordWrap are deprecated) 2 - To strip whitespace from the label's text, as it will cause the resizing to fail (you don't want to know how long it took me to find that bug)

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

提交回复
热议问题