Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set NSAttributedString range?

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?

like image 998
Stefan Avatar asked Jun 02 '17 16:06

Stefan


2 Answers

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

like image 192
Fernando Mazzon Avatar answered Nov 08 '22 06:11

Fernando Mazzon


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
like image 35
Mahdi Moqadasi Avatar answered Nov 08 '22 06:11

Mahdi Moqadasi