可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.