4

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?

Stefan
  • 908
  • 1
  • 11
  • 33
  • I think this is answered here. http://stackoverflow.com/questions/3527494/how-to-calculate-uilabel-width-based-on-text-length Hope, it helps – Arpit Jain Apr 11 '17 at 05:40

4 Answers4

12

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.

Sakir Sherasiya
  • 1,562
  • 1
  • 17
  • 31
  • It works but I needed it like this: lblDemo.widthAnchor.constraint(equalToConstant: 30+lblDemo.intrinsicContentSize.width).isActive = true I used 30 more of labels own width. – Umut ADALI Jun 08 '18 at 14:18
1
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

Baran Karaoğuz
  • 236
  • 1
  • 12
0

You can cast the string you are setting the label's text value to type NSString.

guard let labelText = label.text else { return }    
let castString = labelText as NSString
let size: CGSize = castString.size(attributes: [NSFontAttributeName : UIFont.systemFontSize])

//you now can use size.width to apply to a desired view
syllabix
  • 2,240
  • 17
  • 16
0

You want to get width of label based on text entered. I think you will find appropriate solution here

How to calculate UILabel width based on text length?

Hope, it helps

Community
  • 1
  • 1
Arpit Jain
  • 1,660
  • 12
  • 23