Home > front end >  How to adjust the height of the textview depends on the content in correct way?
How to adjust the height of the textview depends on the content in correct way?

Time:06-30

I have tried 2 more methods. But those are not giving me the correct solution.
If i tried this one

 func textViewDidChange(_ textView: UITextView) {
        self.comments.translatesAutoresizingMaskIntoConstraints = true
        self.comments.sizeToFit()
        self.comments.isScrollEnabled = false
    }

i can only type a one letter per a line.

If i tried this one

 func textViewDidChange(_ textView: UITextView) {
self.comments.translatesAutoresizingMaskIntoConstraints = true
self.comments.isScrollEnabled = false
let fixedWidth = passedOut.frame.size.width
let newSize = comments.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
comments.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    }

Its working. But at the viewDidLoad stage, the width of textview is certain less than which i constraints to the textview. But i gave the leading, trailing , height as same as passedOut textfield to that textview.

If i start typing in textview,This image shown at viewDidLoad when i m using second method the width of textview will become exact size which i want.

So pls suggest me what mistake i made?

CodePudding user response:

  1. Assign a height constraint to the text view

  2. Use the following method to change the height:

     func textViewDidChange(_ textView: UITextView) {
        let size = textView.bounds.size
        let newSize = textView.sizeThatFits(
         CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude)
        )
    
        if size.height != newSize.height {
            self.userMessageTextViewHeightConstraint.constant = newSize.height
            textView.layoutIfNeeded()
        }
     }
    

CodePudding user response:

You can achieve this behavior by doing 2 things in textview

  1. Disable scrolling in textview
  2. Assign the following constraints to textview

a) leading

b) trailing

c) top

d) height >= 30 ,assuming 30 is the minimum height of your textview.

Now when your text will grow textview will grow with it.

  • Related