How To Customize Strings in Swift? Old but Gold: NSAttributedString


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.


Here, we created an attributed string by adding font and color attributes to a static text.

Change font and size of attributed string in Swift

Now, let’s change the attributes of a substring in a string.


Font & Size:

Use NSAttributedString.Key.font to change style and size.

Change font and size of attributed string in Swift

Shadow:

Use NSAttributedString.Key.shadow to add shadow.

Add shadow to attributed string in Swift

Foreground Color:

Use NSAttributedString.Key.foregroundColor to change foreground color.

Change foreground color of attributed string in Swift

Background Color:

Use NSAttributedString.Key.backgroundColor to change background color.

Change background color of attributed string in Swift

Underline:

Use NSAttributedString.Key.underlineStyle to add underline.

Add underline to attributed string in Swift

Link:

Use NSAttributedString.Key.link to add link.

Add link to attributed string in Swift

Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “How To Customize Strings in Swift? Old but Gold: NSAttributedString