0
votes

I have a multiple UILabels. When the device size changes the width and height of the labels changes, so I scale down the text so it fits inside the label. What I want to do is get the font size from one label, and set it as the font size of the other labels, so that everything fits inside the labels, but are also the same size.

This is my code for rescaling the text:

Name_Label.numberOfLines = 1
Name_Label.adjustsFontSizeToFitWidth = true
Name_Label.lineBreakMode = NSLineBreakMode.ByClipping

I can get the point size as other answers have suggested:

Year_Label.font.fontWithSize(Name_Label.font.pointSize)

But this does not work, and comments suggest that this does not return the font size. So how do I get the font size of a label that has just been scaled down, and use that to set the other labels font size?

UPDATE: When I print the following code the output is the same, however in the simulator the size is different.

Year_Label.font = Name_Label.font
2

2 Answers

0
votes

You can use this class to fit labels size. Just tell that your label is this class. There you as well can set if it should check horizontally or vertically. https://github.com/VolodymyrKhmil/BBBLibs/tree/master/BBBAutoresizedFontLabel

Hope it helps.

0
votes

After doing more research, I found a function in Swift 3 that worked. However, to change the size you have to set the Minimum Font Scale (Which I forgot to do). Below is the code in Swift 2 that works:

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    Name_Label.numberOfLines = 1
    Name_Label.adjustsFontSizeToFitWidth = true
    Name_Label.lineBreakMode = NSLineBreakMode.ByClipping

    func adjustedFontSizeForLabel(label: UILabel) -> CGFloat {
        let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)
        text.setAttributes([NSFontAttributeName: label.font], range: NSMakeRange(0, text.length))
        let context: NSStringDrawingContext = NSStringDrawingContext()
        context.minimumScaleFactor = label.minimumScaleFactor
        text.boundingRectWithSize(label.frame.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: context)
        let adjustedFontSize: CGFloat = label.font.pointSize * context.actualScaleFactor
        return adjustedFontSize
    }


    Name_Label.font = Name_Label.font.fontWithSize(adjustedFontSizeForLabel(Name_Label))
    Year_Label.font = Year_Label.font.fontWithSize(adjustedFontSizeForLabel(Name_Label))
    House_Label.font = House_Label.font.fontWithSize(adjustedFontSizeForLabel(Name_Label))
}

Link to source: https://stackoverflow.com/a/38568278/6421669