Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel text with different font size and color [duplicate]

Tags:

ios

uilabel

swift

Howto set different font size and color in a UILabel with Swift?

I need to color the first char of the string with different color and size than the rest of the string.

like image 325
lifeisfoo Avatar asked Jan 15 '16 14:01

lifeisfoo


1 Answers

Suppose you want to have a smaller and gray currency symbol like this:

enter image description here

Just use a NSMutableAttributedString object:

let amountText = NSMutableAttributedString.init(string: "€ 60,00")

// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12), 
                              NSForegroundColorAttributeName: UIColor.grayColor()],
                         range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times

// set the attributed string to the UILabel object
myUILabel.attributedText = amountText

Swift 5.3:

let amountText = NSMutableAttributedString.init(string: "€ 60,00")

// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
                              NSAttributedString.Key.foregroundColor: UIColor.gray],
                             range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times
// set the attributed string to the UILabel object

// set the attributed string to the UILabel object
myUILabel.attributedText = amountText
like image 200
lifeisfoo Avatar answered Nov 14 '22 14:11

lifeisfoo