Alan Alan - 10 days ago 7
iOS Question

Multiline UIButton with each line truncated independently

I'm trying to make a multiline button by subclassing UIButton. To avoid drawing two custom

UILabel
(I'm still pretty new to Swift/Xcode), I'm using attributed strings for the existing
UILabel
and splitting lines with a new line character, like so:

func prepareAttributedTitle(_ primaryTitle: String = "", _ secondaryTitle: String = "") {
let title = NSMutableAttributedString()
let first = NSAttributedString(string: primaryTitle, attributes: [
NSForegroundColorAttributeName: tintColor,
NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightSemibold)
])
let newLine = NSAttributedString(string: "\n")
let second = NSAttributedString(string: secondaryTitle, attributes: [
NSForegroundColorAttributeName: tintColor.withAlphaComponent(0.75),
NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
])

title.append(first)
title.append(newLine)
title.append(second)

setAttributedTitle(title, for: .normal)
}


And the result is (sorry, I don't have enough rep to post images):

| This is the long first |
| line |
| Secondary line |


However, I'd like to truncate lines independently, like this:

| This is the long fi... |
| Secondary line |


Is there a way to do this without using two custom UILabels?

Thanks

Answer

A single UILabel does not support what you need. You will have to use two single-line labels each set with tail truncation.