Search code examples
iosinterface-buildernsattributedstringios-darkmode

How to use dynamic colors in attributed strings via interface builder?


According to Implementing Dark Mode on iOS we need to set the foregroundColor attribute to the new label color. How is this done with interface builder?

I tried using the "Text Color" option and setting the color to Developer->labelColor, but that did not work.

EDIT: As this is currently not possible, I used this workaround:

override func viewDidLoad() {
    // Support Dark Mode
    if #available(iOS 13.0, *) {
        let attributes = NSMutableAttributedString(attributedString: textView.attributedText!)
        attributes.addAttribute(.foregroundColor, value: UIColor.label, range: NSRange(location: 0, length: attributes.mutableString.length))
        textView.attributedText = attributes
    }
}

Solution

  • You can't do this in Interface Builder. You'll have to set the .foregroundColor attribute in code.

    let mas = NSMutableAttributedString(string:s, attributes:[
        .font:UIFont(name:"GillSans", size:15)!,
        .foregroundColor:UIColor.label,
    ]