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

拜拜、爱过 提交于 2019-12-25 17:19:50

问题


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:

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?


回答1:


Use this:

‏‏‎ ‏‏‎

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




回答2:


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

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

Result:

https://i.imgur.com/ju2hfd0.jpg




回答3:


You can force the text of any UITextView to have padding, i.e., to be indented from its edges – by setting its textContainerInset property to a value of your choosing. For example, to give a text view insets of 50 points from the bottom edge, you would use this code:

Swift version: 5.0

textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)


来源:https://stackoverflow.com/questions/56298892/extra-whitespace-that-causes-a-newline-by-uitextview-at-end-is-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!