Adjust UILabel height to text

181,425

Solution 1

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
}

enter image description here

Solution 2

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

enter image description here

For iOS7

  • First, you need to add contains height for UILabel
  • Then, modify the Relation from Equal to Greater than or Equal

enter image description here

  • Finally, change the lines of UILabel from 1 to 0

enter image description here

Your UILabel will automatically increase height depending on the text

Solution 3

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

Solution 4

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)

Solution 5

I create this extension if you want

extension UILabel {
    func setSizeFont (sizeFont: CGFloat) {
        self.font =  UIFont(name: self.font.fontName, size: sizeFont)!
        self.sizeToFit()
    }
}
Share:
181,425
TheBurgerShot
Author by

TheBurgerShot

I have experience (from previous projects) in: Native Android Development (Java) Native iOS Development (Objective-C, Swift) NodeJS Currently programming mostly in/with: Angular 2+ Ionic 2+ React Native PHP 5.6/7+ (Laravel 4/5) HTML, CSS, JavaScript, TypeScript Other things I got the hang of: Server management and security (Ubuntu) Database Architectures

Updated on November 25, 2021

Comments

  • TheBurgerShot
    TheBurgerShot over 2 years

    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!

  • TheBurgerShot
    TheBurgerShot almost 10 years
    this works fine for mee too in playground, the error does not seem to occur at this specific place, when i remove the usages of this method it is gonna whine about some println's or just a line with only comments (then it says EXC_BAD_ACCESS code=2 as well)
  • Unome
    Unome over 9 years
    It works in a playground, but no sizing occurs as desired inside of a view controller in XCode 6.1
  • Zorayr
    Zorayr almost 9 years
    I am a little hesitant to create a new UILabel per sizing; if this method is used inside layoutSubviews with the tendency to be invoked multiple times per complete layout, the extra object creation may introduce noticeable delays, especially during scrolling.
  • oyalhi
    oyalhi over 8 years
    And if the label is inside a cell. When and how would you increase the cell height accordingly?
  • Coder_A_D
    Coder_A_D over 8 years
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping this line helped me thanks.
  • TheBurgerShot
    TheBurgerShot over 8 years
    This does not make the UILabel to adjust it's height.
  • Linh
    Linh about 8 years
    @oyalhi, if your label is inside a tableview cell, please see my other post stackoverflow.com/a/36277840/5381331
  • Bill Thompson
    Bill Thompson about 8 years
    This worked perfectly for me! Setup the constraints, and it will work properly!
  • gadget00
    gadget00 about 8 years
    not working for me...the word "Label" in a UILabel makes height=20. It remains 20 after this setting.
  • Siddharth Pancholi
    Siddharth Pancholi about 8 years
    let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
  • Rouny
    Rouny about 7 years
    I am unable to call this function in my view controller...Can you suggest me what could be the possible reason?
  • Yannis
    Yannis over 6 years
    Code-only answers are not considered good practice. Please consider adding some explanations on how your answer addresses the question.
  • Saeed Rahmatolahi
    Saeed Rahmatolahi about 6 years
    this will not working as I expected I want the label size equal to my view and height be dynamic depend on text and label be at the bottom of the view how can I do that ?
  • Amg91
    Amg91 over 5 years
    Cannot assign to property: 'height' is a get-only property.
  • John Pitts
    John Pitts almost 3 years
    No idea what "add contains height for UILabel" means, and there is no "Height Constraint" section in UIBuilder with First Item (pictured)??
  • Jatezzz
    Jatezzz over 2 years
    proved.. thanks!