0

I have a dynamically changing text in TextView.I could not be able to get the content Height of TextView.

Here is what i tried.

let height = self.tvComment.contentSize.height
print("height",height)

let contentSizeComment = self.tvComment.sizeThatFits(self.tvComment.bounds.size)
print("height",contentSizeComment)

Why it's not getting the content height of TextView? Hope you understand my problem. Thanks in Advance

Kuldeep
  • 4,466
  • 8
  • 32
  • 59
John
  • 3,769
  • 4
  • 12
  • 23

3 Answers3

0

Usethis method to get the height -

func heightForString(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.size.height
}
Pankaj
  • 397
  • 1
  • 3
  • 13
0

in textdidchange you can use this code,in order to resize when textchange

//approxi should be the width of your textview
           let approxi = view.frame.width - 90
//size is the max width and height of textview,1000 can be what ever you want
            let size = CGSize(width: approxi, height: 1000)


   //dont forget to put your font and size
//chey is the text of thetext view
                let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 15)]
                let estim = NSString(string: chey).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)

//estim is height

above it the first method,second method will come in edit second method is

    func pva()  {
//what was the name of my textfield
            let fixedwidth = what.frame.size.width - 40
            let newsize = what.contentSize.height
            self.hrightext.constant = newsize
            self.view.layoutIfNeeded()

        }

note: both are tested and works in swift4

Abd
  • 497
  • 4
  • 14
0

Your just write code in below delegate of UITextView:-

func textViewDidChange(_ textView: UITextView!) {

    let height = self.tvComment.contentSize.height
    print("height",height)

    let contentSizeComment = self.tvComment.sizeThatFits(self.tvComment.bounds.size)
    print("height",contentSizeComment)
}

I hope it help you,

Thank you.

V D Purohit
  • 1,179
  • 1
  • 10
  • 23