'UITextView.attributedText, How to set numberOflines and lineBreakMode?
In some condition I have to use UITextView instead of UILabel(To make link attributes clickable). Here is my code:
let attributedString = NSMutableAttributedString(string: "TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest")
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
And here is my textView:
private lazy var titleTextView: UITextView = {
let view = UITextView(frame: .zero, textContainer: nil)
view.isEditable = false
view.textContainerInset = .zero
view.textContainer.lineFragmentPadding = 0
view.textContainer.maximumNumberOfLines = 2 // Set numberOflines here!
view.textAlignment = .left
view.isScrollEnabled = false
view.delegate = self
return view
}()
But maximumNumberOfLines property don't work, it display only 1 line and followed by "..."
Solution 1:[1]
You need to set the lineBreakMode
to a value that doesn't truncate.
Try
paragraphStyle.lineBreakMode = .byWordWrapping
Solution 2:[2]
When i set the linespacing property, the size computered by UITextView.sizeToFit() is not height enough to display more than 1 line. But in UILabel, call sizeToFit will computer a appropriate height for you to display as more lines as you want.
Solution 3:[3]
Try:
view.textContainer.maximumNumberOfLines = 2
view.textContainer.lineBreakMode = .byTruncatingTail
Solution 4:[4]
removing linebreakmode
of paragraphStyle
used by attributed text works for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dave Weston |
Solution 2 | Maize |
Solution 3 | linhey |
Solution 4 | SwissMark |