JosieGPT
JosieGPT

Reputation: 137

UITextView doesn't print text on the nextLine?

I put the UITextView inside a UIView. The UIView expands as the user types in the UITextView but the problem is that if the user types on the next line, it doesn't show the text being typed until the user types on the third line, then it shows the text printed on the second line. Same goes with the 3rd line and 4th line, etc.

How can I fix this?

func textViewDidChange(_ textView: UITextView) {
    print(textView.text)
    let size = CGSize(width: prayerRequest.frame.width, height: .infinity)

    let estimatedSize = textView.sizeThatFits(size)
    textView.constraints.forEach { (constraints) in
        if constraints.firstAttribute == .height {
            constraints.constant = estimatedSize.height

        }

        viewContainer.constraints.forEach({ (constraints) in
            if constraints.firstAttribute == .height {
                constraints.constant = estimatedSize.height
                viewContainer.layoutIfNeeded()
            }
        })
    }

}

Upvotes: 0

Views: 452

Answers (2)

Bhagyesh
Bhagyesh

Reputation: 144

First of all, you don't need to set height for textView's Parent. Even if you do set the low priority for textView's parent.

See the image, Purple being parent and Yellow is textView.

enter image description here

In viewDidLoad, add the following code:

textView.textContainerInset = UIEdgeInsets.zero
textView.textContainer.lineFragmentPadding = 0

Then, implement textView Delegate method:

extension ViewController : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        let textHeight = textView.attributedText.boundingRect(with: 
            CGSize.init(width: textView.frame.width, height: .infinity),
               options:[.usesLineFragmentOrigin, .usesFontLeading],
               context: nil).height

        if previousHeight != textHeight {
            previousHeight = textHeight
            print("Height text: \(textHeight)")
            textViewHeight.constant = textHeight
            self.view.layoutIfNeeded()
            textView.setContentOffset(.zero, animated: false)
        }
    }
}

textViewHeight is height constraint of textView. Initialize var previousHeight = CGFloat(0) as instance variable. It will help limit calls to layoutIfNeeded to only when the height is changed.

Bottom constraint of the textView will expand parent view. So you do not need to set Parent's height as well.

Upvotes: 0

Edvinas
Edvinas

Reputation: 147

If you're using interface builder try setting the number of lines to 0.

Or from code textView.textContainer.maximumNumberOfLines = 10

Upvotes: 1

Related Questions