Using basic HTML in Labels on iOS like Android

For Android, MobileWeb and Tizen, labels support a html property that can take simple HTML to display formatted text. Since Titanium 3.2.0 we have support for attributedStrings on iOS, which can also be used to format text.

Attributed Strings are complex

However, constructing an Attributed String object is complex and not something you can sent from your back-end.

Parsing HTML to an Attributed String

To solve this, I’ve created a HTML to Attributed String module for Titanium and added a Label-tag to my XP.UI library for Alloy.


You can now have the following in Alloy:

    <Label module="xp.ui" html="<font size=17>Hello <b>Bold</b> <font color=#FF0000>World!</font></font>" />

And get the same result on both iOS and Android:

See the module’s README for more details.

Alternative: WebViews

A workaround that we all have used for formatting text is displaying it in a WebView or ti.styledlabel which effectively is a light WebView. Both of these take a lot more resources then Attributed Strings.

Known issues

There are some known issues:

  • TC-4987: Setting the Label’s color property will override any colors set in the HTML / Attributed String in some cases. Work around this by only setting colors in HTML.
  • TC-4991 Setting a font-weight (<b> or <strong>) or font-family (<font face="Arial">) will also change the font-size, while setting the font-size via the Label’s font property has no effect. Work around this by wrapping the HTML in a font-tag setting the default size.
  • TC-4988: Setting the attributedString property will not override the text property, like the documentation says it will. Work around this by simply not setting the text property.
  • TC-4993: Links in the HTML are always blue and underlined. When used with a TextArea the links are a different kind of blue and not underlined.
  • TC-4992: Links in the HTML only fire the link event on a long press. Work around this by using a TextArea instead, which has a handleLinks property which if set to true will make it work for a single tap as well.
  • TC-4994: In Alloy, using quotes in the html attribute (html="<font color=\"red\">red</font>" will give a compiler error. The correct way to escape this would be html="<font color=&quot;red&quot;>red</font>" or html='<font color="red">red</font>'

App imagineer: Imagining, Engineering & Speaking about Native mobile Apps with Appcelerator Titanium & Alloy • Meetup organizer • Certified Expert • Titan