0

I am trying to measure the height of lines to place an overlay over specific text in a UITextView. Specifically what I mean by lines is text delimitated with \n. So one line can actually span multiple lines and that is what I am trying to measure. I have tried a few different approaches, however, I can't seem to calculate the height correctly. Another weakness with my current approaches is it has to be all calculated on the main synchronous thread which is less than ideal because I have a lot calculations to do.

EXAMPLE UI APPROACH

measurement.font = UIFont(name: "Menlo", size: 16)
measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)

func heightForString(line: String) -> CGFloat {
    var height : CGFloat = 0
    measurement.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 10000)
    measurement.sizeToFit()
    height = measurement.frame.height
    print(height, lineHeight)
    measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)
    return height
}
// Comparing the returned height to measurement.font?.lineHeight and padding shows the results make little sense... :(

EXAMPLE PRINT

Should be 1 line

30.0 18.625

Should be 3 lines

43.6666666666667 18.625

Anters Bear
  • 1,816
  • 1
  • 15
  • 41

1 Answers1

1
func heightForString(line: String) -> CGFloat {
    let textView = UITextView()
    let maxwidth = UIScreen.main.bounds.width
    textView.frame = CGRect(x:0,y: 0,width: maxwidth,height: CGFloat(MAXFLOAT))
    textView.textContainerInset = UIEdgeInsets.zero
    textView.textContainer.lineFragmentPadding = 0
    textView.font = UIFont(name: "Menlo", size: 16)
    textView.text = line
    textView.isScrollEnabled = false
    textView.sizeToFit()
    return textView.frame.size.height
}
sohan vanani
  • 1,537
  • 1
  • 20
  • 37