14

A little confused with using the syntax. I know you are supposed to use NSFontAttributeName, however I don't know how to correctly specify the range.

I'm curious about two cases.

How do I specify the range for all characters in the text, and how do I specify the range as something like the first 10 characters.

Any suggestions?

Stefan
  • 908
  • 1
  • 11
  • 33

2 Answers2

26

Don't use magic numbers

let baseString = "Don't use magic numbers."

let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)

let dontRange = (attributedString.string as NSString).range(of: "Don't")
attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)], range: dontRange)

So meta

Fernando Mazzon
  • 3,562
  • 1
  • 19
  • 21
6

In XCode 10 and swift 4 I used this way:

let customizedText = NSMutableAttributedString(string: "My Text")
customizedText.addAttribute(NSAttributedString.Key.strokeWidth, value: 5.0, range: NSRange(location: 0, length: customizedText.string.count))
customizedText.addAttribute(NSAttributedString.Key.strokeColor, value: #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1), range: NSRange(location: 0, length: customizedText.string.count))
myLabel.attributedText = customizedText
Mahdi Moqadasi
  • 2,029
  • 4
  • 26
  • 52