1

how can I know the height of the text inside this textView?

lazy var textView: UITextView = {
    let tv = UITextView()
    tv.textColor = .white
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.isEditable = false
    tv.backgroundColor = .white
    tv.text = "Se non vuoi vedere di nuovo questa presentazione clicca sul bottone qui sotto..."
    tv.textAlignment = .center
    tv.font = UIFont(name: "Avenir-Light", size: 22)
    return tv
}()

3 Answers3

17

You can calculate text height like below:

let sizeThatFitsTextView = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat(MAXFLOAT)))
let heightOfText = sizeThatFitsTextView.height
kamil3
  • 1,232
  • 1
  • 14
  • 19
2

in My case i am calculating Height of Label

func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
    {
        let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text

        label.sizeToFit()



        return label.frame.height

    }
Manvir Singh
  • 129
  • 2
  • 11
0

I found this..in my case it works:

func returnStringWidth(font: UIFont, text: String) -> CGSize {
    let fontAttributes = [NSFontAttributeName: font]
    let size = (text as NSString).size(attributes: fontAttributes)

    return size
}