How to turn an AttributeContainer into an NSAttributedString.Key dictionary

Hi, guys. While trying to update the old code to the new AttributedString structure I realized that there are properties in UIKit that take a dictionary of NSAttributedString.Key values. For instance, the code below assigns a dictionary to the titleTextAttributes property of the UINavigationBarAppearance object. This property doesn't take an AttributeContainer value and I couldn't find any way to convert the container into a dictionary. Is there a way to do it or do we still have to use the old NSAttributedString.Key values in these cases?

Thanks!


class ViewController: UIViewController {
   override func viewDidLoad() {
    super.viewDidLoad()
    let standard = UINavigationBarAppearance()
    standard.titleTextAttributes = [.foregroundColor: UIColor.red]
    navigationController?.navigationBar.standardAppearance = standard
   }
}
Answered by Frameworks Engineer in 679810022

You can convert an AttributeContainer to a [NSAttributedString.Key : Any] dictionary using this Dictionary(_: AttributeContainer, including: KeyPath) conversion initializer. For example:

var container = AttributeContainer()
container.foregroundColor = UIColor.red
// ...
standard.titleTextAttributes = try? Dictionary(container, including: \.uiKit)
Accepted Answer

You can convert an AttributeContainer to a [NSAttributedString.Key : Any] dictionary using this Dictionary(_: AttributeContainer, including: KeyPath) conversion initializer. For example:

var container = AttributeContainer()
container.foregroundColor = UIColor.red
// ...
standard.titleTextAttributes = try? Dictionary(container, including: \.uiKit)
How to turn an AttributeContainer into an NSAttributedString.Key dictionary
 
 
Q