How to check current font size of UILabel? - ios

I have 3 UILabels and I want to set same (the smallest one from all of 3 possibilities) font for all of them. What is the problem? I don't know how to check the current font - each of UILabels use Autoshrink with minimal font scale and lines amount equaled to 0. The text of UILabels is set in ViewDidLoad() method (there are many combinations of possible label texts).
I tried to get the current font size with UILabel.font.pointSize property (called in viewDidAppear() method) and than compare all of them. The problem is that that UILabel.font.pointSize returns not current value of UILabel text font size (after Autoshrink has been done) but the value that is set in storyboard.
I'm totally out of ideas so thanks for the help!
Greetings, John

use this extention
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
}
get height
height = strDesc.height(withConstrainedWidth: UIScreen.main.bounds.size.width - 160, font: UIFont.systemFont(ofSize: 14.0))

This is one way to get the current size of the UILabel pointsize although I know of more ways if this does not work. This is the cleanest and fastest. See example and extension included.
import UIKit
class ViewController: UIViewController {
lazy var label1 : UILabel = {
let lbl = UILabel(frame: CGRect(x: 20, y: 80, width: self.view.bounds.width - 40, height: 40))
lbl.text = "This is some large text to make it fit to size with a big font size"
lbl.font = UIFont.systemFont(ofSize: 50, weight: .bold)
lbl.textColor = .black
lbl.minimumScaleFactor = 0.01
lbl.adjustsFontSizeToFitWidth = true
lbl.numberOfLines = 0
return lbl
}()
lazy var label2 : UILabel = {
let lbl = UILabel(frame: CGRect(x: 20, y: label1.frame.maxY + 5, width: self.view.bounds.width - 40, height: 40))
lbl.text = "This is one line"
lbl.font = UIFont.systemFont(ofSize: 20, weight: .bold)
lbl.textColor = .black
lbl.minimumScaleFactor = 0.01
lbl.adjustsFontSizeToFitWidth = true
lbl.numberOfLines = 0
return lbl
}()
lazy var label3 : UILabel = {
let lbl = UILabel(frame: CGRect(x: 20, y: label2.frame.maxY + 10, width: self.view.bounds.width - 40, height: 80))
lbl.text = "This is some large text to make it fit to size with a big font size"
lbl.font = UIFont.systemFont(ofSize: 100, weight: .bold)
lbl.textColor = .black
lbl.minimumScaleFactor = 0.01
lbl.adjustsFontSizeToFitWidth = true
lbl.numberOfLines = 0
return lbl
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(label1)
self.view.addSubview(label2)
self.view.addSubview(label3)
var minSize : CGFloat = .greatestFiniteMagnitude
for sub in self.view.subviews{
if let lbl = sub as? UILabel{
//get the size
let font = lbl.adjustedFont()
print("the size is \(font.pointSize)")
minSize = min(font.pointSize,minSize)
}
}
print("the minimum for all fonts is \(minSize)")
print("i am going to delay for 3 seconds and then reset all the labels to the minimum size :)")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.0) {
for sub in self.view.subviews{
if let lbl = sub as? UILabel{
lbl.font = lbl.font.withSize(minSize)
}
}
}
}
}
extension UILabel{
func adjustedFont()->UIFont {
guard let txt = text else {
return self.font
}
let attributes: [NSAttributedString.Key: Any] = [.font: self.font]
let attributedString = NSAttributedString(string: txt, attributes: attributes)
let drawingContext = NSStringDrawingContext()
drawingContext.minimumScaleFactor = self.minimumScaleFactor
attributedString.boundingRect(with: bounds.size,
options: [.usesLineFragmentOrigin,.usesFontLeading],
context: drawingContext)
let fontSize = font.pointSize * drawingContext.actualScaleFactor
return font.withSize(CGFloat(floor(Double(fontSize))))
}
}
Example in Action

What I've found is that inside viewDidLoad() your constraints are not fully defined yet. You can try to do these calculations in another method for example viewWillAppear() or any other that suits you and is executed after viewDidLoad().

Related

How to create dynamic label size programmatically in swift?

I'm trying to create a label programmatically in Swift but the issue I'm having is that based on the data model the amount of text can change thereby changing the size of the label. Typically I would create the label like this before knowing the text:
headerLabel.frame = CGRect(x: 0, y: 0, width: screenSize.width/2.5, height: screenSize.height/45)
headerLabel.center = CGPoint(x: screenSize.width/2, y: 245)
But in this case the text can be any amount ranging from a line to a paragraph so hard coding the height won't work. How to create the label so it would accommodate any amount of text?
You can access label intrinsic property after you have given the text to label then you can give the frame.
Swift 3:
let label = UILabel()
label.text = "Your text here"
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 14)
label.frame = CGRect(x:0,y:0,width:label.intrinsicContentSize.width,height:label.intrinsicContentSize.height)
you can check some conditions based on the intrinsicContentSize.
Hope it helps.
This label has a defined width but not a defined height. The height is determined by the amount of text in the label. If you removed the width, the label would not break into lines, which is not what you want. The sizeToFit() method called at the end sets the height of the label after it knows how many lines of text it needs to break into based on the label's text. If this isn't what you wanted, let me know.
let label = UILabel()
label.text = "scones"
label.numberOfLines = 0 // 0 = as many lines as the label needs
label.frame.origin.x = 32
label.frame.origin.y = 32
label.frame.size.width = view.bounds.width - 64
label.font = UIFont.displayHeavy(size: 17) // my UIFont extension
label.textColor = UIColor.black
label.sizeToFit()
view.addSubview(label)
You can use the following to calculate the string height and width and then set them:
import Foundation
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let width = "Hello World".stringWidth // 74.6
let height = "Hello World".stringHeight // 16.7
let headerLabel = UILabel()
headerLabel.frame = CGRect(x: 0, y: 0, width: width, height: height)
headerLabel.center = CGPoint(x: screenSize.width/2, y: 245)
}
}
extension String {
var stringWidth: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.width
}
var stringHeight: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.height
}
}

How to set label height for auto adjust in Read More/Less with Swift 3?

I would like to create the paragraph with Read More/Read Less at the end. Here are my codes;
func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
let lbl = UILabel(frame: .zero)
lbl.frame.size.width = width
lbl.font = font
lbl.numberOfLines = 0
lbl.text = text
lbl.sizeToFit()
lbl.adjustsFontSizeToFitWidth = true
return lbl.frame.size.height
}
#IBAction func btnReadMore(_ sender: Any) {
if isLabelAtMaxHeight {
btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal)
btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
isLabelAtMaxHeight = false
lblReviewHeight.constant = 29
lblReview.font = UIFont (name: "Tharlon", size: 13)
}
else {
btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal)
btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
isLabelAtMaxHeight = true
lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font)
lblReview.font = UIFont (name: "Tharlon", size: 13)
lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead
}
}
I also set the label "Word wrap" in Attributes Inspector.
The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.
So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.
I don't want to use any other library.
Could anyone help me please?
Remove constraint lblReviewHeight, then just try to use numberOfLines control your text layout, if your want show all description set numberOfLines = 0, otherwise set numberOfLines to the line you want.
to calculate text height by font and width you can use this extension
extension UIFont {
func sizeOfString (_ string: String, constrainedToWidth width: CGFloat) -> CGSize {
return NSString(string: string).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: self],
context: nil).size
}
}
then call it
let width = 290.0
let textSize = UIFont.systemFont(ofSize: 15).sizeOfString("text", constrainedToWidth: width)

resizing UILabels based on total width of text

How would I go about predicting the required width of a UILabel based on it's font size and number of characters in the label's text.
I have seen a few examples of this being done, however they are all in objective-c not swift 3.0.
I found this method but it's in objective-c and I'm having trouble implementing it.
CGFloat width = [label.text sizeWithFont:[UIFont systemFontOfSize:17.0f]].width;
Any suggestions?
If Want to Make size of UILabel Based on TextSize and TextLength then use
intrinsicContentSize.
Below is sample code for that:
lblDemo.frame.size = lblDemo.intrinsicContentSize
Here lblDemo is IBOutlet of UILabel.
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let text = "Size To Fit Tutorial"
let font : UIFont!
switch UIDevice.current.userInterfaceIdiom {
case .pad:
font = UIFont(name: "Helvetica", size: 35)
case .phone:
font = UIFont(name: "Helvetica", size: 50)
default:
font = UIFont(name: "Helvetica", size: 24)
}
let yourHeight = heightForLabel(text: text, font: font, width:
screenWidth)
let yourLabel : UILabel = UILabel(Frame : CGRect(x:0 ,y:0
,width:screenWidth ,height:yourHeight))
yourLabel.backgroundColor = UIColor.black
self.view.addSubviews(yourLabel)
}
//Self Sizing height ....
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width:
width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byCharWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
Hope, it helps
You can cast the string you are setting the label's text value to type NSString.
guard let labelText = label.text else { return }
let castString = labelText as NSString
let size: CGSize = castString.size(attributes: [NSFontAttributeName : UIFont.systemFontSize])
//you now can use size.width to apply to a desired view
You want to get width of label based on text entered. I think you will find appropriate solution here
How to calculate UILabel width based on text length?
Hope, it helps

How to give dynamic height to UILabel programmatically in Swift?

I have taken UIlabel which are generated dynamically using for loop, each type diff text is assign in label, I want to give UILabel size dynamically depending on text.
Is there any easy solution in to do that in Swift?
let label:UILabel = UILabel(frame: CGRectMake(x, y, width, height))
label.numberOfLines = 4
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
let font = UIFont(name: "Helvetica", size: 20.0)
label.font = font
label.text = "Whatever you want the text enter here"
label.sizeToFit()
If you want to set numberOfLines according to the content of text,give your maximum lines.That is very important here.
get a label height depending on it's text, font, and width you assign to it:
func rectForText(text: String, font: UIFont, maxSize: CGSize) -> CGSize {
let attrString = NSAttributedString.init(string: text, attributes: [NSFontAttributeName:font])
let rect = attrString.boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
let size = CGSizeMake(rect.size.width, rect.size.height)
return size
}
let labelSize = rectForText("your text here", font: UIFont.systemFontOfSize(your font), maxSize: CGSizeMake(your label width,999))
let labelHeight = labelSize.height //here it is!
myLabel.text = "Your Label Text Here"
myLabel.textAlignment = .Natural
myLabel.numberOfLines = 0
myLabel.sizeToFit()
myLabel.frame = CGRectMake(myLabel.frame.origin.x, myLabel.frame.origin.y, 280, myLabel.frame.height)
Create Extension to calculate the height of label following method return height of the label
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 60)
let label:UILabel = UILabel()
label.textColor=UIColor.black
label.font = UIFont(name: "Halvetica", size: 17)
label.numberOfLines = 1
label.text = item.name
label.sizeToFit()
label.frame = CGRect(x: 5, y: imageView.frame.height+10, width: 50, height:label.frame.height)
let label = UILabel()
label.backgroundColor = UIColor.greenColor()
label.text = "Hello,world.\n Just a test."
let font = UIFont.systemFontOfSize(17.0)
label.font = font
label.numberOfLines = 0;
let text = label.text! as NSString
let size = text.sizeWithAttributes([NSFontAttributeName:font])
label.frame = CGRectMake(0, 0, size.width, size.height)
You can use Auto Layout in code. See Auto Layout Guide
The Swift 4.1 extension method to calculate label height:
extension UILabel {
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
Refer: Adjust UILabel height to text
NSString(string: "hello this is a string").boundingRect(
with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: self],
context: nil).size
Use this method to get determine the size for you string. Put maximum height and maximum width in CGSize(widhth,height) and it will return CGSize object containing height and width. Use it according with your scenario

Adjust UILabel height to text

I have some labels which I want to adjust their height to the text, this is the code I wrote for this now
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
EDIT:
The issue was not in this piece of code, so my fix is in the question itself. It might still be useful for others!
I've just put this in a playground and it works for me.
Updated for Swift 4.0
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 100.0)
Swift 3:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
If you are using AutoLayout, you can adjust UILabel height by config UI only.
For iOS8 or above
Set constraint leading/trailing for your UILabel
And change the lines of UILabel from 1 to 0
For iOS7
First, you need to add contains height for UILabel
Then, modify the Relation from Equal to Greater than or Equal
Finally, change the lines of UILabel from 1 to 0
Your UILabel will automatically increase height depending on the text
In swift 4.1 and Xcode 9.4.1
Only 3 steps
Step 1)
//To calculate height for label based on text size and width
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
Step 2)
//Call this function
let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
print(height)//Output : 41.0
Step 3)
//This is your label
let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
proNameLbl.text = "This is your text"
proNameLbl.font = UIFont.systemFont(ofSize: 17)
proNameLbl.numberOfLines = 0
proNameLbl.lineBreakMode = .byWordWrapping
infoView.addSubview(proNameLbl)
I have the strong working solution.
in layoutSubviews:
title.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0)
title.sizeToFit()
title.frame.size = title.bounds.size
in text setter:
title.text = newValue
setNeedsLayout()
UPD.
of course with this UILabel settings:
title.lineBreakMode = .byWordWrapping
title.numberOfLines = 0
I create this extension if you want
extension UILabel {
func setSizeFont (sizeFont: CGFloat) {
self.font = UIFont(name: self.font.fontName, size: sizeFont)!
self.sizeToFit()
}
}
based on Anorak's answer, I also agree with Zorayr's concern, so I added a couple of lines to remove the UILabel and return only the CGFloat, I don't know if it helps since the original code doesn't add the UIabel, but it doesn't throw error, so I'm using the code below:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
var currHeight:CGFloat!
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
currHeight = label.frame.height
label.removeFromSuperview()
return currHeight
}
Just by setting:
label.numberOfLines = 0
The label automatically adjusts its height based upon the amount of text entered.
The solution suggested by Anorak as a computed property in an extension for UILabel:
extension UILabel
{
var optimalHeight : CGFloat
{
get
{
let label = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = self.lineBreakMode
label.font = self.font
label.text = self.text
label.sizeToFit()
return label.frame.height
}
}
}
Usage:
self.brandModelLabel.frame.size.height = self.brandModelLabel.optimalHeight
Following on #Anorak answer, i added this extension to String and sent an inset as a parameter, because a lot of times you will need a padding to your text.
Anyway, maybe some you will find this usefull.
extension String {
func heightForWithFont(font: UIFont, width: CGFloat, insets: UIEdgeInsets) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width + insets.left + insets.right, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height + insets.top + insets.bottom
}
}
Here is how to calculate the text height in Swift. You can then get the height from the rect and set the constraint height of the label or textView, etc.
let font = UIFont(name: "HelveticaNeue", size: 25)!
let text = "This is some really long text just to test how it works for calculating heights in swift of string sizes. What if I add a couple lines of text?"
let textString = text as NSString
let textAttributes = [NSFontAttributeName: font]
let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
just call this method where you need dynamic Height for label
func getHeightforController(view: AnyObject) -> CGFloat {
let tempView: UILabel = view as! UILabel
var context: NSStringDrawingContext = NSStringDrawingContext()
context.minimumScaleFactor = 0.8
var width: CGFloat = tempView.frame.size.width
width = ((UIScreen.mainScreen().bounds.width)/320)*width
let size: CGSize = tempView.text!.boundingRectWithSize(CGSizeMake(width, 2000), options:NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: tempView.font], context: context).size as CGSize
return size.height
}
Swift 4.0
self.messageLabel = UILabel(frame: CGRect(x: 70, y: 60, width:UIScreen.main.bounds.width - 80, height: 30)
messageLabel.text = message
messageLabel.lineBreakMode = .byWordWrapping //in versions below swift 3 (messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping)
messageLabel.numberOfLines = 0 //To write any number of lines within a label scope
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor.white
messageLabel.font = messageLabel.font.withSize(12)
messageLabel.sizeToFit()
Blockquote NSParagraphStyle.LineBreakMode, apply to entire paragraphs, not words within paragraphs.This property is in effect both during normal drawing and in cases where the font size must be reduced to fit the label’s text in its bounding box. This property is set to byTruncatingTail by default.
This link describes the storyboard way of doing the same
Swift 4.0
Instead of calculating the text/label height, I just resize the label after inserting the (dynamic) text.
Assuming that myLabel is the UILabel in question:
let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: *somewidth*, height: *placeholder, e.g. 20*))
myLabel.numberOfLines = 0
myLabel.lineBreakMode = .byWordWrapping
...
And now comes the fun part:
var myLabelText: String = "" {
didSet {
myLabel.text = myLabelText
myLabel.sizeToFit()
}
}
The Swift 4.1 extension method to calculate label height:
extension UILabel {
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
Swift 5, XCode 11 storyboard way. I think this works for iOS 9 and higher. You want for example "Description" label to get the dynamic height, follow the steps:
1) Select description label -> Go to Attributes Inspector (pencil icon), set:
Lines: 0
Line Break: Word Wrap
2) Select your UILabel from storyboard and go to Size Inspector (ruler icon),
3) Go down to "Content Compression Resistance Priority to 1 for all other UIView (lables, buttons, imageview, etc) components that are interacting with your label.
For example, I have UIImageView, Title Label, and Description Label vertically in my view. I set Content Compression Resistance Priority to UIImageView and title label to 1 and for description label to 750. This will make a description label to take as much as needed height.
You can also use sizeThatFits function.
For example:
label.sizeThatFits(superView.frame.size).height
To make label dynamic in swift , don't give height constarint and in storyboard make label number of lines 0 also give bottom constraint and this is the best way i am handling dynamic label as per their content size .

Resources