skip to Main Content

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?

2

Answers


    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()
          }
       }
      
    Login or Signup to reply.
  1. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search