Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Monotouch/Xamarin.iOS - UILabel with both plain and italic text in a single string

I have a string of text containing both plain and italic text. How do I represent this using a UILabel?

"I am plain text whereas I am italic text

var someText = "I am plain text whereas I am italic text

UILabel myLabel = new UILabel(new RectangleF(0,0,100,40));
myLabel.Text = someText;
like image 932
Goober Avatar asked Feb 14 '23 00:02

Goober


2 Answers

I prefer to concatenate like this:

var text = new NSMutableAttributedString (
               str: "I am plain text whereas ", 
               font: UIFont.SystemFontOfSize (14f)
               );

text.Append (new NSMutableAttributedString (
               str: "I am italic text.", 
               font: UIFont.ItalicSystemFontOfSize (14f)
               ));

var label = new UILabel () { AttributedText = text };

Seems easier to maintain this way instead of counting characters. But I totally agree - all of this AttributedString stuff is hacky. Jason's link to the docs was helpful, thanks.

like image 155
Ender2050 Avatar answered Mar 05 '23 16:03

Ender2050


UILabel has an AttributedText property, which you can use to style text.

var prettyString = new NSMutableAttributedString ("UITextField is not pretty!");
prettyString.SetAttributes (firstAttributes.Dictionary, new NSRange (0, 11));
prettyString.SetAttributes (secondAttributes.Dictionary, new NSRange (15, 3));
prettyString.SetAttributes (thirdAttributes.Dictionary, new NSRange (19, 6));

A complete sample is available in the Xamarin Docs.

like image 36
Jason Avatar answered Mar 05 '23 16:03

Jason