Wednesday, May 25, 2022

AttributedString Attribute Scopes

Natalia Panferova:

UIKit and AppKit attribute scopes have many attributes with matching names but different value types. Attributes with types defined in UIKit such as UIColor, UIFont etc. are available on platforms that can import UIKit and attributes with types defined in AppKit such as NSColor, NSFont etc. are available on macOS. AttributeScopes.UIKitAttributes type contains the full list of UIKit attributes and AttributeScopes.AppKitAttributes contains the full list of AppKit attributes.

Foundation can infer the right type of the attribute to use when we assign the value. The following code will assign as foreground color when UIKit is imported and when AppKit is imported.


Note, that when SwiftUI is imported SwiftUI attributes take priority and the resulting attribute value will be that is defined in the SwiftUI framework.


We can even define our own attributes and attribute scopes. This can be useful if we are building a framework or a package or just want to extend AttributedString functionality in our app.

See also: NSAttributedStringBuilder (via Kaya Thomas).


Comments RSS · Twitter

Leave a Comment