I am trying to create a UILabel
which contains two texts of different fonts where one NSMutableAttributedString
sits vertically on top of the other. Upon attempting to insert a line break via swift’s n
I found that the appended string disappears. I have tried a variety of lineBreakMode
s with no result (with and without n
) along with ensuring the frame isnt constricting the texts visibility by setting a large maximumLineHeight
.
I should also mention that according to Apple’s documentation when setting UILabel.attributedText
to any NSAttributedText
instance
When the label has an attributed string value, the system ignores the textColor, font, textAlignment, lineBreakMode, and lineBreakStrategy properties. Set the foregroundColor, font, alignment, lineBreakMode, and lineBreakStrategy properties in the attributed string instead.
Here is some of the code simplified for the sake of the question (I have also tried calling .sizeTofit()
after setting the labels attributedText
as well as setting different .lineBreakStrategy
s)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byWordWrapping
let totalVisitsString = NSMutableAttributedString(string: "(visitLogs.count)n", attributes: [.font : UIFont.systemFont(ofSize: 25), .paragraphStyle : paragraphStyle])
totalVisitsString.append(NSMutableAttributedString(string: "Total visits", attributes: [.font : UIFont.systemFont(ofSize: 14)]))
totalVisitsLabel.attributedText = totalVisitsString
the label itself:
var totalVisitsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
2
Answers
By default your label’s
numberOfLines
is 1. You never change it so that is what you get.Labels when created are defaulted to 1 line. You’ll need to set the number of lines to 0 (unlimited) or whatever number you want to max it at.