If you run the code snippet below, it will show incorrect text in the last line that has the ... ellipsis, as show in this image:
Once you change the lineBreakMode to byWordWrapping, or set the numberOfLines to 0, then the text is displayed correctly. Also, if you remove the line break /n from the text, then the text is displayed correctly.
So my question is: How can I use a /n line break in the text in a UILabel with a limited numberOfLines and lineBreakMode .byTruncatingTail without showing incorrect text on the last line?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let text = "A line break challenge \nInvestigating a bug where the text in the last line is incorrect when numberOfLines is limited to for example 3. Very strange indeed. Peculiar. What to do about this? What am I missing?"
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail //.byWordWrapping works, but not what I want.
let attributedString = NSAttributedString(string: text, attributes: [
.paragraphStyle: paragraphStyle
])
let label = UILabel()
label.attributedText = attributedString
label.numberOfLines = 3 //0 works, but is not what I want.
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0).isActive = true
label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20.0).isActive = true
label.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20.0).isActive = true
}
}
