Alan Alan - 1 year ago 122
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

(I'm still pretty new to Swift/Xcode), I'm using attributed strings for the existing
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)


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?


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download