Related: How To Use NSAttributedString in SwiftUI: Hack It!
We use NSAttributedString to create different styled texts in Swift. There are many options to modify in this class.
To understand how it works, let’s get started with a simple attributed string example.
let str = "Coffee Break Codes" var attribute = [NSAttributedString.Key: AnyObject]() attribute[.font] = UIFont.systemFont(ofSize: 12) attribute[.foregroundColor] = UIColor.black let attributedStr = NSMutableAttributedString(string: str, attributes: attribute)
Here, we created an attributed string by adding font and color attributes to a static text.

Now, let’s change the attributes of a substring in a string.
Font & Size:
let str = "SwiftUI: change font of substring iPhone"
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 22),
range: NSString(string: str).range(of: "iPhone"))
Use NSAttributedString.Key.font to change style and size.

Shadow:
let str = "SwiftUI: add shadow to the substring Batman"
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 2, height: 2)
shadow.shadowBlurRadius = 4
shadow.shadowColor = UIColor.black
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.shadow,
value: shadow,
range: NSString(string: str).range(of: "Batman"))
Use NSAttributedString.Key.shadow to add shadow.

Foreground Color:
let str = "SwiftUI: change color of substring: iOS in purple"
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.purple,
range: NSString(string: str).range(of: "iOS"))
Use NSAttributedString.Key.foregroundColor to change foreground color.

Background Color:
let str = "SwiftUI: change background color of substring Superman in red"
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.backgroundColor,
value: UIColor.red,
range: NSString(string: str).range(of: "Superman"))
Use NSAttributedString.Key.backgroundColor to change background color.

Underline:
let str = "SwiftUI: underline a specific keyword: Coffee, nothing else!"
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSString(string: str).range(of: "Coffee"))
Use NSAttributedString.Key.underlineStyle to add underline.

Link:
let str = "SwiftUI: add link to a substring Click Here"
var attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(
NSAttributedString.Key.link,
value: "coffeebreakcodes.com",
range: NSString(string: str).range(of: "Click Here"))
Use NSAttributedString.Key.link to add link.


Pingback: How To Use NSAttributedString in SwiftUI: Hack It!