NSAttributedString Enhancements in iOS 11

Tags: , ,

An NSAttributedString can be a pain to configure in the way that you want. The attributes dictionary has always been a dictionary comprised of StringAny pairs. There have been some nice enhancments in iOS 11, though.

In iOS 10, the keys, which are defined in the NSAttributedString, looked something like NSForegroundColorAttributeName. The keys are simply constants for a String. It could be difficult to find the one you want though, because auto-complete did not work great unless you knew what you were looking for. If the names looked more like NSAttribuedNameForegroundColor, code completion would have worked much better.

Now, in iOS 11, the NSAttributedString changes have gone even further to become easy to work with. The attributes dictionary has been changed to NSAttributedStringKeyAny pairs. NSAttributedStringKey is a struct and all of the keys that you can work with in an NSAttributedString have static properties on that struct. So, when trying to find a attribute, we can now get code completion help very easily.

Code Completion for NSAttributedString

Code Comparison

The code for building an attributes dictionary does not look very different, but for a quick comparison, here is an attributes dictionary created in Xcode 8 for iOS 10.

let attributes: [String : Any] =
            [NSForegroundColorAttributeName: UIColor.purple,
             NSFontAttributeName: UIFont(name: "Papya", size:20) ??
                                  UIFont.systemFont(ofSize: 20),
             NSUnderlineColorAttributeName: UIColor.purple,
             NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]

And, here are the same attributes in Xcode 9 beta for iOS 11.

let attributes: [NSAttributedStringKey : Any] =
            [.paragraphStyle: paragraphStyle,
             .foregroundColor: UIColor.purple,
             .font: UIFont(name: "Papya", size:20) ??
                    UIFont.systemFont(ofSize: 20),
             .underlineColor: UIColor.purple,
             .underlineStyle: NSUnderlineStyle.styleSingle.rawValue]