What to use for AttributeName in Xamarin Mac

2020-08-23 01:44发布

问题:

I'm trying to colorize a substring in my NSMutableAttributedString in Xamarin, but it seems to be missing the proper constants,

What should I put there?

Update. This gets closer:

var s = new NSMutableAttributedString ("hello");
s.AddAttribute (CTStringAttributeKey.ForegroundColor , NSColor.Red, new NSRange (0, 3));
wordLabel.AttributedStringValue = s;

and gives

though the color on screen is still black text!

Update2 Maybe CTStringAttributeKey is the wrong one, but there is no NSStringAttributeKey

回答1:

Ok, so I looked at the API and it seems it's there, just under NSAttributedString

ForegroundColorAttributeName

So use something like:

s.AddAttribute(NSAttributedString.ForegroundColorAttributeName, NSColor.Red, new NSRange(0,3));


回答2:

In case people are wondering what the equivalent is for Xamarin iOS, here it is: The foreground color attribute name can be found here: UIStringAttributeKey.ForegroundColor

Also NSColor.Red should be UIColor.Red

So adding an attribute should look like:

s.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, new NSRange(0,3));


回答3:

Important:

The keys in Xamarin.Mac have changed from NSAttributedString to NSStringAttributeKey so this:

s.AddAttribute(NSAttributedString.ForegroundColorAttributeName, NSColor.Red, new NSRange(0,3));

Should be:

s.AddAttribute(NSStringAttributeKey.ForegroundColorAttributeName, NSColor.Red, new NSRange(0,3));


回答4:

I can confirm that what was stated above is the correct answer:

s.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, new NSRange(0,3));

The NSRange value appears to relate to the length of the string. So if the string is 5 characters long, the NSRange should be NSRange(0, 5).



回答5:

I couldn't make the above solutions work because it could not convert from NSMutableAttributedString to UIStringAttributes. So after playing a little bit with the code I got this working solution:

UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes
{
    ForegroundColor = UIColor.White
};

This is for Xamarin.iOS, complementing Mike Richards answer. I've never developed for Xamarin.Mac, so I don't know if it would work there.



标签: c# xamarin