1

i have an extension to UILabel that suppose to calculate it's frame.

func getFrameWithAlreadySetTextAndFont() -> CGRect {
    let label = UILabel()
    label.text = self.text
    label.font = self.font
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.frame.size.width = CGFloat(MAXFLOAT)
    label.frame.size.height = CGFloat(MAXFLOAT)
    label.sizeToFit()
    return label.frame
  }

Now, i want to calculate expected text frame for my label.

let lbl = LabelSL.extraLarge()
lbl.text = "357"
let expectedLabelFrame = lbl.getFrameWithAlreadySetTextAndFont()

Ok, i got:

expected frame (0.0, 0.0, 42.5, 29.0)

enter image description here

That is frame of label i can see in debugger.

But what i actually want is text frame:

enter image description here

The same as previous, but without extra spaces. How can i get it?

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • Have you tried [`textRect`](https://developer.apple.com/documentation/uikit/uilabel/1620545-textrect) or [`boundingRect `](https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrect) – dahiya_boy Oct 15 '19 at 09:05
  • @dahiya_boy just tried, it still have same output. – Evgeniy Kleban Oct 15 '19 at 09:06
  • 1
    This answer on stackoverflow should help https://stackoverflow.com/a/21267507/3564632 coming from this article: https://spin.atomicobject.com/2017/08/04/swift-extending-uilabel/. – denis_lor Oct 15 '19 at 09:45
  • 1
    Also this can help: https://stackoverflow.com/questions/27459746/adding-space-padding-to-a-uilabel/44145859#44145859 – denis_lor Oct 15 '19 at 09:51
  • Possible duplicate of [Resizing a UILabel to accommodate insets](https://stackoverflow.com/questions/21167226/resizing-a-uilabel-to-accommodate-insets) – denis_lor Oct 15 '19 at 09:53

0 Answers0