I have a UILabel with text
Choose Pasta: Fettuccine
Add Toppings To The Pasta: Side Meatball
Substitute Alfredo Sauce: Substitute Alfredo Sauce On Pasta
Choose A Complimentary Soup Or Salad: Zuppa Toscana
How do I apply different fonts Bold & Normal for this UILabel so that it displays like
Choose Pasta: Fettuccine Add Toppings To The Pasta: Side Meatball Substitute Alfredo Sauce: Substitute Alfredo Sauce On Pasta Choose A Complimentary Soup Or Salad: Zuppa Toscana
The part before : as Bold & the part after : as normal font
Any help/suggestions would be appreciated...
Build an NSAttributedString
and set it as the label's attributedText
property.
Example:
let html = "<strong>Choose Pasta</strong>: Fettuccine <strong>Add Toppings To The Pasta</strong>: Side Meatball <strong>Substitute Alfredo Sauce</strong>: Substitute Alfredo Sauce On Pasta <strong>Choose A Complimentary Soup Or Salad</strong>: Zuppa Toscana"
let richText = try NSAttributedString(
data: html.dataUsingEncoding(NSUTF8StringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding],
documentAttributes: nil)
label.attributedText = richText
If you'd rather assign the attributes in code:
let richText = NSMutableAttributedString()
let normalAttributes = [ NSFontAttributeName: UIFont.systemFontOfSize(12) ]
let boldAttributes = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(12) ]
richText.appendAttributedString(NSAttributedString(string: "Choose Pasta", attributes: boldAttributes))
richText.appendAttributedString(NSAttributedString(string: ": Fettucine ", attributes: normalAttributes))
richText.appendAttributedString(NSAttributedString(string: "Add Toppings To The Pasta", attributes: boldAttributes))
richText.appendAttributedString(NSAttributedString(string: ": Side Meatball ", attributes: normalAttributes))
// etc.
label.attributedText = richText