This is my method:
extension String {
func height(with font: UIFont, forWidth width: CGFloat) -> CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
label.setDynamicFont(font)
label.numberOfLines = 0
label.text = self
label.sizeToFit()
return label.frame.height
}
}
extension UIView {
func setDynamicFont(_ font: UIFont) {
enableDynamicFont()
if let label = self as? UILabel {
label.font = font.scaled
}
}
func enableDynamicFont() {
if let adjustable = self as? UIContentSizeCategoryAdjusting {
adjustable.adjustsFontForContentSizeCategory = true
}
maximumContentSizeCategory = .extraExtraExtraLarge
}
}
extension UIFont {
static var poppinsRegular: UIFont {
UIFont(name: "Poppins-Regular", size: 16)!
}
var scaled: UIFont {
UIFontMetrics.default.scaledFont(for: self)
}
}
How do I use it?
contentTextView.snp.updateConstraints { maker in
maker.height.equalTo(height(for: message.attributedText.string))
}
How do I define height for my label?
private func height(for text: String) -> CGFloat {
let font = UIFont.poppinsRegular.withSize(16)
print("::: text: (text)")
print("::: width: (contentTextView.frame.width)")
print("::: height: (text.height(with: font, forWidth: contentTextView.frame.width))")
return text.height(with: font, forWidth: contentTextView.frame.width)
}
The output on console is the following:
::: text: abcsruweź udział w ankiecie, liczy się każdy głos, twoja opinia ma dla nas bardzo duże znaczenie, cenimy Twoją opinię, podziel sie z nami tym co myslisz Dlugga nazwa ankiety, sie zastanawiam czy ma wplyw na ucinanie linkow weź udział w ankiecie, liczy się każdy głos, twoja opinia ma dla nas bardzo duże znaczenie, cenimy Twoją opinię, podziel sie z nami tym co myslisz Dlugga nazwa ankiety, sie zastanawiam czy ma wplyw na ucinanie linkow ::: width: 304.0 ::: height: 291.3333333333333
and the result in app:
As you can see it is not fully displayed. Why?
Recognized by Mobile Development Collective