Swift - Adjusting fontSize to fit the width of the

2019-04-03 04:10发布

问题:

I've been looking for something to dynamically adjust my fontSize to fit the width of my layout box. But all the answers I can find, is either to use this:

label.adjustsFontSizeToFitWidth = true

Which does work. But only if I don't have setTranslatesAutoresizingMaskIntoConstraints set to false.

Please note that I don't use storyboards. So to have full control over my other constraints I need this line:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

So how can I adjust the font size to fit the width without using storyboard and when I can't use adjustsFontSizeToFitWidth.

After I figure out how to adjust the font size to fit the width. I also need to adjust the height of the layout box to fit the font size. There seems to be documentation on that though, but if you happen to know the answer of this as well, it would be greatly appreciated.

Thanks in advance

回答1:

Try the following commands for your label:

label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.2

And try to change the lines of the label to 0 and 1 (check both cases):

label.numberOfLines = 0 // or 1


回答2:

MinimumScaleFactor range is 0 to 1. So we are setting the MinimumScaleFactor with respect to our font size as follows

Objective C

[lb setMinimumScaleFactor:10.0/[UIFont labelFontSize]]; lb.adjustsFontSizeToFitWidth = YES;

Swift 3.0

lb.minimumScaleFactor = 10/UIFont.labelFontSize lb.adjustsFontSizeToFitWidth = true



回答3:

I don't know if this will completely answer your question, but you can use this extension to calculate your own font sizes to fit.

extension String {
   func height(constrainedBy width: CGFloat, with font: UIFont) -> CGFloat {
       let constraintSize = CGSize(width: width, height: .max)
       let boundingBox = self.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

       return boundingBox.height
   }

   func width(constrainedBy height: CGFloat, with font: UIFont) -> CGFloat {
       let constrainedSize = CGSize(width: .max, height: height)
       let boundingBox = self.boundingRectWithSize(constrainedSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

       return boundingBox.width
   }
}


回答4:

I just did that you needed , Works perfectly ! (Programmatically ONLY) - We are setting large font size to the label , in order to re-scale it to the perfect font size.

self.label.font = UIFont(name: "Heiti TC", size: 60)
self.label.numberOfLines = 0
self.label.minimumScaleFactor = 0.1
self.label.baselineAdjustment = .alignCenters
self.label.textAlignment  = .center

If you are using AutoLayout, implement this code in viewDidLayoutSubviews (after the layout has been laid out).

Yours, Roi



回答5:

Here's a hack solution:

var size: CGFloat = 20

    while titleLabel.frame.width > containerView.frame.width {

        titleLabel.font = UIFont.systemFont(ofSize: size)
        titleLabel.sizeToFit()
        size -= 1

    }


回答6:

Swift 4 conversion of above:

extension String
{
    func height(constrainedBy width: CGFloat, with font: UIFont) -> CGFloat
    {
        let constraintSize = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return boundingBox.height
    }

    func width(constrainedBy height: CGFloat, with font: UIFont) -> CGFloat
    {
        let constrainedSize = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return boundingBox.width
    }
}


回答7:

I had a similar problem using a UILabel inside a UITableViewCell and my cell's were adjusting their heights dynamically as well (refer to this if you wanna know more about dynamic cell heights: https://www.raywenderlich.com/129059/self-sizing-table-view-cells)

And no matter what I did for the mimimum font scale, it wasn't working. Turns out, for this feature to work you also have to set the Line Break property to Truncate Tail or Middle or Head. If you have Word Wrap or Character Wrap it won't dynamically scale down your UILabel font (I had a custom font created called: Title 2).

Hope this helps someone else trying to figure this out.

Here is a screenshot of my UILabel properties: