Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resizing UILabels based on total width of text

How would I go about predicting the required width of a UILabel based on it's font size and number of characters in the label's text.

I have seen a few examples of this being done, however they are all in objective-c not swift 3.0.

I found this method but it's in objective-c and I'm having trouble implementing it.

CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:17.0f]].width;

Any suggestions?

like image 662
Stefan Avatar asked Oct 26 '25 16:10

Stefan


2 Answers

If Want to Make size of UILabel Based on TextSize and TextLength then use intrinsicContentSize.

Below is sample code for that:

lblDemo.frame.size = lblDemo.intrinsicContentSize

Here lblDemo is IBOutlet of UILabel.

like image 80
Sakir Sherasiya Avatar answered Oct 29 '25 06:10

Sakir Sherasiya


override func viewDidLoad() {
  super.viewDidLoad()
  let screenSize = UIScreen.main.bounds
  let screenWidth = screenSize.width
  let text = "Size To Fit Tutorial"
  let font : UIFont!
  switch UIDevice.current.userInterfaceIdiom {
  case .pad:
    font = UIFont(name: "Helvetica", size: 35)
  case .phone:
    font = UIFont(name: "Helvetica", size: 50)
  default:
    font = UIFont(name: "Helvetica", size: 24)
}
  let yourHeight = heightForLabel(text: text, font: font, width: 
  screenWidth)

  let yourLabel : UILabel = UILabel(Frame : CGRect(x:0 ,y:0 
  ,width:screenWidth ,height:yourHeight))
  yourLabel.backgroundColor = UIColor.black
  self.view.addSubviews(yourLabel)

}


//Self Sizing height ....
func heightForLabel(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.byCharWrapping
   label.font = font
   label.text = text
   label.sizeToFit()
   return label.frame.height
}

Hope, it helps

like image 34
Baran Karaoğuz Avatar answered Oct 29 '25 07:10

Baran Karaoğuz