Sunday, 28 December 2014

Swift + Get Height of Label Dynamically

func heightForLabel(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

    }




let font = UIFont(name: "Verdana", size: 12)
        var detailHeight = heightForLabel("Your String", font: font!, width: self.scrollView.bounds.size.width-10)

3 comments:

  1. I have been looking for exactly this for 2 months <3

    ReplyDelete
  2. Thank you, this worked for me (using Swift 3)! =D

    ReplyDelete
  3. Man you are fkng genius! Thanks a lot :)

    ReplyDelete