Swift How to calculate the text height of one line from its font

I had a problem when I needed to animate the translation of the label vertically by the same distance of the text textField. In most cases, only textField.bounds.heigt , but if the height of the textField is greater than the height of the text, this will not be good for me. So I need to know: How to calculate the height of a line of text of a line from its UIFont ?

As for the duplicate: There is a little different from what I need. this answer (to which I referred in my answer) gets the overall height depending on 1) line 2) width 3) font. What I needed was the height of one line, dpending only on the font .

+8
string ios height swift uifont
source share
2 answers

UIFont has the UIFont property:

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

where is the font - your font

+11
source share

I was looking for a way to do this and find this answer where it has a String extension to calculate the size of the string and the given font. I modified it to do what I want ( to get the height of a line of text written in font. ):

 extension UIFont { func calculateHeight(text: String, width: CGFloat) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let boundingBox = text.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: self], context: nil) return boundingBox.height } } 

Hope this helps someone find it. (maybe I'm in the future).

+4
source share

All Articles