Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift How to calculate one line text height from its font

I ran into an issue where I needed to animate translating a label vertically the same distance of a textField's text height. In most cases just textField.bounds.heigt but if the textField's height is bigger than the text height it will not be any good for me. So I need to know: How to calculate the line height of the string text from its UIFont?

Regarding the duplicate: There's a little bit different of what I need. that answer(which I've referenced in my answer) get the total height depending on 1) the string 2) the width 3) the font. What I needed is one line height dpending only on the font.

like image 807
Ismail Avatar asked Feb 29 '16 16:02

Ismail


People also ask

How do I calculate text height?

Multiply the drawing scale factor by the desired text output height to determine the height of the text objects in the drawing. Using the drawing scale factor of 48 and a desired text height of 3/16” for the output, you would take 48 x 0.1875 to get a final text height of 9.

How line height work?

The line-height CSS property sets the height of a line box. It's commonly used to set the distance between lines of text. On block-level elements, it specifies the minimum height of line boxes within the element. On non-replaced inline elements, it specifies the height that is used to calculate line box height.

How do I change the text height of a line in SwiftUI?

SwiftUI text does not provide a lineHeight property (line spacing is a different beast). You could try to align the 'firstTextBaseLine' to get the desired behaviour. Alternatively, use a 'UILabel' (via 'UIViewRepresentable') with an attributed string (specify line height in the paragraph style).


1 Answers

UIFont has a property lineHeight:

    if let font = _textView.font {
        let height = font.lineHeight
    }

where font is your font

like image 153
Alexandr Kolesnik Avatar answered Oct 05 '22 12:10

Alexandr Kolesnik