Search code examples
iosswiftuitextfielduitextviewnstextcontainer

Extra whitespace that causes a newline by UITextView at end is ignored


This is my code:

import UIKit

class ViewController: UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)

        let textView = UITextView(frame: .zero)
        textView.isScrollEnabled = false
        textView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textView)

        NSLayoutConstraint.activate([
           textView.widthAnchor.constraint(equalToConstant: 150),
            textView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            textView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])

        // As we can see, LOT'S of whitespace at the end.
        textView.text = "Some Random Text That Has Whitespaces At The End                                                        "

        view.backgroundColor = .yellow
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }
}

This is the result:

enter image description here

By the amount of spaces, it should have created an empty newline. However, as we can see this wasn't the case. If I add another character at the very end of the string, the newline will be shown (but with the character, which I do not want).

How can I show an empty newline if needed in an UITextView?


Solution

  • Use this:

    ‏‏‎ ‏‏‎

    There is some invisible characters inside the quote that iOS is not count them as whiteSpace