Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give dynamic height to UILabel programmatically in Swift?

Tags:

ios

swift

iphone

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?

like image 746
New iOS Dev Avatar asked Jul 05 '15 09:07

New iOS Dev


2 Answers

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.

like image 200
user3182143 Avatar answered Nov 16 '22 04:11

user3182143


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!
like image 37
bluenowhere Avatar answered Nov 16 '22 04:11

bluenowhere