What to use for AttributeName in Xamarin Mac

I am trying to colorize a substring in my NSMutableAttributedString in Xamarin, but it seems to lack the correct constants,

enter image description here

What should I do there?

Update . This is approaching:

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

and gives

enter image description here

although the color on the screen is still black text!

enter image description here

Update2 Perhaps CTStringAttributeKey is incorrect, but no NSStringAttributeKey

enter image description here

+8
c # xamarin
source share
5 answers

Ok, so I looked at the API and it seems there, just below NSAttributedString

ForegroundColorAttributeName

So use something like:

 s.AddAttribute(NSAttributedString.ForegroundColorAttributeName, NSColor.Red, new NSRange(0,3)); 
+6
source share

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

Also NSColor.Red should be UIColor.Red

Therefore, adding an attribute should look like this:

 s.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, new NSRange(0,3)); 
+10
source share

Important:

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

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

Must be:

 s.AddAttribute(NSStringAttributeKey.ForegroundColorAttributeName, NSColor.Red, new NSRange(0,3)); 
+5
source share

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

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

The value of NSRange seems to refer to the length of the string. Therefore, if a string of length 5 long, NSRange must be NSRange(0, 5) .

+1
source share

I could not get these solutions to work because it could not convert from NSMutableAttributedString to UIStringAttributes . Therefore, after playing with the code a bit, I got this working solution:

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

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

0
source share

All Articles