AVEbrahimi
AVEbrahimi

Reputation: 19154

Multiline multicolor attributed text in swift

How can I build something like this using attributed text? I tried adding line feed (\n), it didn't work, just displayed first line and cropped next two, removing \n will display two parts in single line:

let mutableAttributedString = NSMutableAttributedString()

let regularAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 45.0), NSAttributedStringKey.foregroundColor: UIColor.yellow]
let boldAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 25.0), NSAttributedStringKey.foregroundColor: UIColor.white]     

let mutableAttributedString2 = NSMutableAttributedString()
let boldAttributedString = NSAttributedString(string: "person", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "\(self.requestCount)", attributes: regularAttribute)
mutableAttributedString2.append(boldAttributedString)
mutableAttributedString2.append(NSAttributedString(string: "\n"))
mutableAttributedString2.append(regularAttributedString)

self.btnStatsPeople.setAttributedTitle(mutableAttributedString2, for: .normal)

Upvotes: 0

Views: 512

Answers (1)

ezaji
ezaji

Reputation: 304

UILabel has one line by default.

This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.

UIButton creates default UILabel. So using 0 lines is a solution for your problem:

self.btnStatsPeople.titleLabel?.numberOfLines = 0

Upvotes: 1

Related Questions