UITextView removing interim blank lines on resize

92 views Asked by At

I have a UITextView that can potentially change size. Scrolling is disabled. Here what's happening:

Is there any way to prevent this strange behaviour but also keep the lineBreakMode to .byTruncatingTail? (removing this option produces the expected resize result)

The playground code so you can reproduce this easily:

import UIKit
import PlaygroundSupport

class HostController: UIViewController {
    let textView = UITextView()
    override func viewDidLoad() {
        view.backgroundColor = .gray
        
        textView.frame = CGRect(x: 10, y: 10, width: 150, height: 200)
        textView.isEditable = false
        textView.isScrollEnabled = false
        textView.textContainer.lineBreakMode = .byTruncatingTail
        textView.text = "Line 1\n\n\n\nLine 2\n\nLine 3\n\nLine 4\nSome text that goes beyond the width"
        view.addSubview(textView)
        
        let slider = UISlider(frame: CGRect(x: 160, y: 10, width: 100, height: 30))
        slider.minimumValue = 10
        slider.maximumValue = 200
        slider.value = 200
        slider.addTarget(self, action: #selector(sliderChanged(sender:)), for: .valueChanged)
        view.addSubview(slider)
    }
    
    @objc func sliderChanged(sender: UISlider) {
        textView.frame.size.height = CGFloat(sender.value)
    }
}

let vc = HostController()
PlaygroundPage.current.liveView = vc
1

There are 1 answers

0
Astri On

Turns out that if you add an empty space character between the new lines the problem is disappearing. For the example above, that would be:

textView.text = "Line 1\n \n \n \nLine 2\n \nLine 3\n \nLine 4\nSome text that goes beyond the width"