简体   繁体   中英

UITextView removing interim blank lines on resize

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM