Custom Xamarin.iOS UILabel attributes using Xamarin Workbooks

Danny Cabrera
2 min readFeb 27, 2018

Needed a way to customize certain text within a UILabel and decided to do a quick post while having fun with Xamarin Workbooks.

UILabelAttributedText Workbook screenshot

In order to customize some text within the UILabel you first need to find its range. To do this create a new NSMutableAttributedString with the text you want to display in the UILabel:

var mutableStr = new NSMutableAttributedString(“My test string.”);

Next, find the range of the text you wish to customize. For this example we’ll locate the range for “test” and apply two attributes, color + font size/bold. The range can be located using our mutable string this way:

var range = mutableStr.MutableString.LocalizedStandardRangeOfString(new NSString(“test”));

Now that we located the range all that’s left is to apply the attributes. First attribute is a blue foreground color:

mutableStr.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Blue, range);

Next let’s make the font bold and increase it to size 30:

mutableStr.AddAttribute(UIStringAttributeKey.Font, UIFont.BoldSystemFontOfSize(30), range);

Once the attributes have been changed all that’s left is to set the attributed text of the label and since I am using Xamarin Workbooks, render the UILabel.

var label = new UILabel(new CGRect(100, 100, 300, 100));
label.AttributedText = mutableStr;
RootViewController.View.AddSubview(label);
iOS Simulator on Windows screenshot

Here’s a link to my workbook UILabelAttributedText.workbook: https://app.box.com/s/bmg93cujthsbka5v99lzfitrn0ijfts5

Xamarin Workbooks is lots of fun and has really saved me time. I don’t have to create console apps to test concepts and minor changes like the example above. All this was done on Windows where I have Visual Studio Studio networked with a Mac. Happy Coding!

--

--