-1

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?

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
J. Doe
  • 12,159
  • 9
  • 60
  • 114

2 Answers2

1

Use this:

‏‏‎ ‏‏‎

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

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • I've used this and it worked for me in 90% of the cases, I have a few where the last line is nonetheless cut off. Do you have any other solution? In my case I'm using a `UILabel` – Niklas Dec 13 '21 at 12:53
  • @Niklas you found a solution? – J. Doe Apr 17 '22 at 16:23
  • Nope. Did you @J.Doe? – Niklas Apr 18 '22 at 19:07
  • @Niklas I have an extremely hacky solution by using NSMutableAttributedString. Long story short: append something like ' |' behind your text, wrap in inside an NSMutableAttributedString and change the color of the last character (which is |) to UIColor.clear. Than it always works in every scenario – J. Doe Apr 19 '22 at 09:31
0

to add extra lines use "\n" for example:

textView.text = "Some Random Text That Has Whitespaces At The End \n\n"

Result:

https://i.stack.imgur.com/QkCmc.jpg

Ludyem
  • 1,709
  • 1
  • 18
  • 33
  • This does not answer the question – J. Doe May 24 '19 at 22:21
  • @J.Doe Post Question: how can I show an empty newline if needed in an UITextView? Answer: to add extra lines use "\n" Did I get it wrong? – Ludyem May 25 '19 at 02:16
  • No. You point out exactly the problem with your answer: you always show a newline. You literally quoted the words 'if needed'. – J. Doe May 25 '19 at 09:30