0

I'm trying to manually size a UITextView so that it exactly fits some text. (I know this can be done with auto layout and disabled scrolling, but that doesn't work here for other reasons.) I'm correctly accounting for textContainerInset and layoutMargins but calculating the line height isn't working.

screen shot

The pic above shows a 120pt font supposedly with a 120pt line height, but clearly the actual line height is 145pts. The question is, how do I calculate that number?

FWIW I checked and the NSParagraphStyle object set on that text view has nothing interesting, ie lineHeightMultiple, lineSpacing, paragraphSpacing are all at their default of 0.0. It's created in the storyboard and none of its layout attributes are changed in code.

Edit: I should have mentioned, this doesn't happen with most fonts. The font I'm currently looking at is called Sahar.

John Scalo
  • 3,194
  • 1
  • 27
  • 35
  • I did find some similar questions (eg https://stackoverflow.com/questions/32764158/uitextview-line-height) but none of them address this exactly. – John Scalo May 03 '21 at 14:39
  • *"... 120pt font supposedly with a 120pt line height ..."* -- I think the key word in that sentence is "**supposedly**". This answer may give you some insight: https://stackoverflow.com/a/33278748/6257435 – DonMag May 03 '21 at 15:30
  • Interesting @DonMag. Unfortunately whereas the UIFont.lineHeight value is clearly smaller than what UITV is using, this calculated version (pointSize + ascender + descender) is clearly _larger_ than what UITV is using. – John Scalo May 03 '21 at 16:06

1 Answers1

1

I added a UITextView in Storyboard and set its font to System Bold 120.0

Then, with this code:

    guard let f = tv.font else {
        return
    }
    
    let l = f.leading
    let a = f.ascender
    let d = f.descender
    
    // descender is a negative value
    let calcLineHeight = l + a + (-d)

    // lineHeight property of font
    let fontLineHeight = f.lineHeight

    print("calculated height:", calcLineHeight)
    print("property height:  ", fontLineHeight)

I get this output (as expected):

calculated height: 143.203125
property height:   143.203125
DonMag
  • 69,424
  • 5
  • 50
  • 86
  • Sorry, @DonMag— I should have mentioned that this doesn't happen with most fonts. I updated the question. – John Scalo May 03 '21 at 17:56
  • 1
    Custom fonts may not always be defined / formatted correctly. I grabbed a free version of Sahar-Heavy, and the "calculated height" I get is 144. If that doesn't work for your needs, then you may need to describe what you're trying to do. Very possibly there is a better (more accurate) way to determine how much space your text needs. – DonMag May 03 '21 at 18:19