Search code examples
swiftuiscrollviewuitextview

TextView in ScrollView - disable auto scroll on typig?


Maybe the problem’s root is in me, but I can’t find an option for disabling the autoscroll on a scrollview that has a textView inside it.

Whenever the user enters a new line at the bottom of the scrollview’s visible area, and continues typing, the scrollview moves along

———-

It is not exaxtly a problem, the problem is that I can not set a “margin” for it preventing the overcrowded look of the UI elements

Images:

(1) what it looks like now entering a new line at the bottom and typing / the scrollView autoscrolls to that pos /

(2) what it should look like

enter image description here

What could I do?


Solution

  • I am doing something similar with UITextView, which has a specified initial height and keeps increasing the height with input text till a maximum specified height and then starts scrolling the text. Let me know is thats something you are looking for.

    enter image description here Single Line enter image description here Two lines enter image description here Three lines enter image description here Four lines enter image description here Stops increasing height

    I am using the delegate method as below. The Height constraints in the below code are IBOutlets from Storyboard.

    func textViewDidChange(_ textView: UITextView) {
        let maxSize = CGSize(width: textView.frame.width, height: 90.0)
        let estimatedSize = textView.sizeThatFits(maxSize)
        if estimatedSize.height <= 90 {
            textView.isScrollEnabled = false
            textViewHeightConstraint.constant = estimatedSize.height
            textViewContainerHeightConstraint.constant = estimatedSize.height + 12.0
        } else {
            textView.isScrollEnabled = false
            textViewHeightConstraint.constant = 90.0
            textViewContainerHeightConstraint.constant = 102.0
        }
    }