I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The \"g\" symbol for grams needs to be attached to my UILabel that I am usin
Swift uses the same NSMutableAttributedString
that Obj-C does. You instantiate it by passing in the calculated value as a string:
var attributedString = NSMutableAttributedString(string:"\(calculatedCoffee)")
Now create the attributed g
string (heh). Note: UIFont.systemFontOfSize(_)
is now a failable initializer, so it has to be unwrapped before you can use it:
var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(19.0)!]
var gString = NSMutableAttributedString(string:"g", attributes:attrs)
And then append it:
attributedString.appendAttributedString(gString)
You can then set the UILabel to display the NSAttributedString like this:
myLabel.attributedText = attributedString
Swift 5 and above
let attributedString = NSAttributedString(string:"targetString",
attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])
Swift 4
let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
You need to remove the raw value in swift 4
The attributes can be setting directly in swift 3...
let attributes = NSAttributedString(string: "String", attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 30)!,
NSForegroundColorAttributeName : UIColor .white,
NSTextEffectAttributeName : NSTextEffectLetterpressStyle])
Then use the variable in any class with attributes