Search code examples
iosswiftswift3nsattributedstring

Swift 3 Error UILabel: the use of CGColor for color properties or inside attributed strings is not supported


My app is crashing when trying to create an NSAttributedString. I'm getting the error:

'NSInternalInconsistencyException', reason: 'UILabel: the use of CGColor for color properties or inside attributed strings is not supported.'

This did not happen before upgrading to Swift 3, Xcode 8

This is my code:

let encodedData = someHtmlString.data(using: String.Encoding.utf8, allowLossyConversion: true)!

let attributedOptions: [String:Any] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                        NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]

do {
    let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
}

I can't understand what CGColor has to do with this.

Edit: I'm using the attributedString like so:

let label = UILabel()
label.text = attributedString.string

But this code is not executed. The app crashes in the 'try' scope.

The string I'm passing in (someHtmlString) has:

<ul>  <li>Up to 2 children 11 years old and younger stay free when occupying the parent or guardian\'s room, using existing bedding. </li><li>Only registered guests are allowed in the guestrooms. </li> <li>The property has connecting/adjoining rooms, which are subject to availability and can be requested by contacting the property using the number on the booking confirmation. </li><li>Some facilities may have restricted access. Guests can contact the property for details using the contact information on the booking confirmation. </li> </ul>

Edit 2 Something weird is happening. I commented out the call to this code, and the app still crashes with the same error. So the "All exceptions" breakpoint was pointing me to the wrong place.

Edit 3 See my solution below


Solution

  • After some commenting out, I found the problem was in this code:

    let mutableAttributedStr = NSMutableAttributedString
    let textColor = label.textColor
    let textRange = NSMakeRange(0, mutableAttributedStr.length)
    mutableAttributedStr.addAttributes([NSForegroundColorAttributeName: textColor], range: textRange)
    

    textColor was resulting in an Optional type (with a value, not nil). Once I added a ! to the following line, it worked. Not sure why this suddenly became an issue in Swift 3/iOS 10.

    let textColor = label.textColor!