Wednesday 21 February 2018

Find Height and Width of Label - Swift

Find Height and Width of Label - Swift

//MARK:- Calculate Height and Width of Label
func heightForLabel(text:String, font:UIFont, width_val:CGFloat) -> CGFloat
{
    var currHeight:CGFloat!

    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width_val, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
   
    currHeight = label.frame.height
    label.removeFromSuperview()
   
    return currHeight
}

func widthForLabel(text:String, font:UIFont, height_val:CGFloat) -> CGFloat
{
    var currWidth:CGFloat!

    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: height_val))
    label.font = font
    label.text = text
    label.sizeToFit()
   
    currWidth = label.frame.width
    label.removeFromSuperview()
   
    return currWidth
}

No comments: