3

I have two UILabel in a custom tableViewCell. One label has width constraints and is set to adjustFontSizeToFitWidth on smaller screens e.g. 5S. How can I get the other UILabel to match the font size of the first label, when it does not have particular width constraints?

It seems sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: was deprecated in iOS7, so what is the Swift solution?

This answer When do adjustsFontSizeToFitWidth or boundingRectWithSize change the context.actualScaleFactor? isn't complete, and I need this to happen in a TableViewCell.

This is what I have in my custom table view cell class. But it is only picking up the original size not the adjusted size.

class CustomTVC: UITableViewCell {

@IBOutlet weak var rowTitle: UILabel!
@IBOutlet weak var rowSubtitle: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // makes the rowSubtitle and title have matching fonts in case of 5S
    let attributes = [NSAttributedStringKey.font: rowTitle.font]
    let textString = rowTitle.text
    let attributedString = NSMutableAttributedString(string:textString!, attributes:attributes)

    let context = NSStringDrawingContext()
    context.minimumScaleFactor = rowTitle.minimumScaleFactor
    let resultingRect = attributedString.boundingRect(with: rowTitle.bounds.size, options: .usesLineFragmentOrigin, context:context)

    print("actual context after drawing: \(context.actualScaleFactor)")

    let actualFontSize = rowTitle.font.pointSize * context.actualScaleFactor
    print("actual font size is: \(actualFontSize)")
}
}
richc
  • 1,648
  • 5
  • 20
  • 48

1 Answers1

-1

this workaround all I can come up with. Hopefully someone will post a better way to actually use adjustSizeToFitWidth.

let ScreenWidth = UIScreen.main.bounds.size.width
    var font = UIFont()
    if ScreenWidth < 321 {
        font = UIFont.systemFont(ofSize: 16, weight: .light)
    } else {
        font = UIFont.systemFont(ofSize: 19, weight: .light)
    }
    rowTitle.font = font
    rowSubtitle.font = font
richc
  • 1,648
  • 5
  • 20
  • 48