xamarinxamarin.iosuicolortttattributedlabel

How to add NSDictionary UIColor in iOS for TTTAttributedLabel LinkAttributes


I have using a Xamarin binding for https://github.com/TTTAttributedLabel/TTTAttributedLabel

And as per - Make link in UILabel.attributedText *not* blue and *not* underlined

self.label.linkAttributes = @{NSForegroundColorAttributeName: color, 
                               NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)};

I would like to set my link attributes, I am just not sure of syntax -

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/Articles/standardAttributes.html

I have tried variations on these -

 label.LinkAttributes = new NSDictionary(
            new NSString("NSForegroundColorAttributeName"), UIColor.Red,
            new NSString("NSUnderlineStyleAttributeName"), new NSUnderlineStyle() == NSUnderlineStyle.Double);

 label.LinkAttributes = new NSDictionary(
            new NSString("NSForegroundColorAttributeName"), UIColor.Red,
            new NSString("NSUnderlineStyleAttributeName"), new NSNumber(2));

But not working. Not sure how to pass in an UIColor as cannot see its Type available, it is doing "something" as its wiped my underline + blue colour with this code.


Solution

  • The following line of code was taken from the github README.md from the project you linked.

    (id)kCTForegroundColorAttributeName : (id)[UIColor redColor].CGColor,
    

    It looks like the library deals with CGColor and not UIColor (or NSColor which are OSX only). There's (too) many ways to represent colours and, sadly, most API only works with one. In this case you'll need to use:

    UIColor.Red.CGColor
    

    instead of:

    UIColor.Red
    

    in the dictionary you give to the LinkAttributes property of your label.

    The key kCTForegroundColorAttributeName (from your comment) must also match Apple's constant value, which can be different than the constant's name. In Xamarin.iOS this constant is exposed as:

    CoreText.CTStringAttributeKey.ForegroundColor
    

    So it the library (re)uses the CoreText constants then this is the value to use.