I am trying to check the colour of specific words in an attributed string. I can access the attribute but can't convert this attribute dictionary into a UIColor.
First I enumerate over my attributed string, this returns, for each different attributed, a dictionary of the attributes. I can then look closer at each.
NSAttributedString * attributes = self.textView.attributedText;
[attributes enumerateAttributesInRange:NSMakeRange(0, attributes.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
}];
When I return the attrs dictionary I get this (with HKWMentionAttributeName being a subclass I am using):
{
HKWMentionAttributeName = "<0x610000243450> (HKWMentionsAttribute) text: ABC name 1, id: uY5Vv8QzBxhPoB8jTxUBeBmTaeD3, no range";
NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
NSFont = "<UICTFont: 0x7fd388558ce0> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 19.00pt";
}
I then access the color with attrs[@"NSColor"];
and it is returned as below:
UIExtendedSRGBColorSpace 1 0 0 1
I can't for the life of me figure out how to turn this into a UIColor or even begin to use this object.
I understand that the 1 0 0 1
are the red, green, blue and alpha but I don't know how to access them to use the colorWithRed
function.
This link seems to suggest I need to change the color space but it doesn't give much more of an explanation than that.
This link makes me feel that I shouldn't be trying to import the NSColor class as it is an OSX class
I have tried all my usual color go-tos: attempting to load as a CGColor
, a CIColor
, loading CGColorGetComponents
, loading it as an NSString
, loading it as an id
to see if this would shine more light on the issue.
I feel this is a problem with my understanding of UIColor
and NSColor
objects but there is very little information I can find which helps convert between the two.
@"NSColor"
, despite coincidentally sharing the name of an AppKit class, is simply the raw value of theNSForegroundColorAttributeName
constant. On iOS, this is documented to be aUIColor
. Therefore, you should just be able to takeattrs[NSForegroundColorAttributeName]
, cast it to aUIColor
, and use it.