Adjust UILabel height to text
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
toGreater than or Equal
- Finally, change the lines of
UILabel
from 1 to 0
Your UILabel
will automatically increase height depending on the text