1

I'm trying to make a text messaging text box that makes the text view bigger and the UIView (in which the text view is contained) bigger as well. I'm working with constraints. When I reach a certain height, I want it to scroll and stop increasing the heights of the container. I've tried all ways possible, including using this forum (How do I size a UITextView to its content?).

One problem occurs when I type it in, once I reach a certain height, it starts typing out of sight below.

func textViewDidChange(textView: UITextView) {

    let fixedWidth = self.chatTextField.frame.size.width
    self.chatTextField.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
    let newSize = self.chatTextField.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
    var newFrame = self.chatTextField.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    print(textViewAnchorHeight?.constant)
    if textView.contentSize.height <= self.chatTextFieldHeightAnchor?.constant {
        textView.scrollEnabled = false
        self.chatTextField.frame = newFrame


        //self.chatTextFieldHeightAnchor?.constant = newSize.height
        self.textViewAnchorHeight?.constant = newSize.height
    } else {
        textView.scrollEnabled = true
        self.automaticallyAdjustsScrollViewInsets = true
        print("here")
    }

What can I do to make the perfect text view?

Community
  • 1
  • 1

1 Answers1

0

You can use the code below to achive that dynamic resize. You might want to change differenceOfHeightvalue to your liking.

func textViewDidChange(textView: UITextView) {
        var newFrame = textView.frame
        var minHeight = 40 // ENTER THE MIN HEIGHT OR THE INITIAL HEIGHT OF THE TEXTVIEW
        var maxHeight = 100 // ENTER THE MAX HEIGHT YOU WANT
        newFrame.size  = textView.sizeThatFits(CGSizeMake(newFrame.size.width, maxHeight)) 

    if newFrame.size.height > minHeight && newFrame.size.height < maxHeight {
        let differenceOfHeight = newFrame.size.height - textView.frame.size.height
        holderView.frame = CGRectMake(holderView.frame.origin.x, holderView.frame.origin.y - differenceOfHeight, holderView.frame.size.width, newFrame.size.height)
        textView.frame = newFrame
    }
}
Ayazmon
  • 1,360
  • 8
  • 17