Skip to content

Instantly share code, notes, and snippets.

@manumaticx
Last active June 8, 2016 16:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manumaticx/8687504 to your computer and use it in GitHub Desktop.
Save manumaticx/8687504 to your computer and use it in GitHub Desktop.
Underline a word in a Ti.UI.Label
/**
* Underlines a single word of a label
* @param {Ti.UI.Label} _label
* @param {String} _word
*/
function underline(_label, _word) {
if (Ti.Platform.name === 'iPhone OS') {
var text = _label.getText();
var attr = Titanium.UI.iOS.createAttributedString({
text : text,
attributes : [{
type : Titanium.UI.iOS.ATTRIBUTE_UNDERLINES_STYLE,
value : Titanium.UI.iOS.ATTRIBUTE_UNDERLINE_STYLE_SINGLE,
range : [text.indexOf(_word), _word.length]
}]
});
_label.setAttributedString(attr); // Why doesn't this work?
}
if (Ti.Platform.osname === 'android') {
var text = _label.text.split(_word);
_label.setHtml(text[0] + '<u>' + _word + '</u>' + text[1]);
_label.setText(undefined);
}
}
// Now you can do this:
var label = Ti.UI.createLabel({
text: 'This is a label with an underlined word in its text.'
});
underline(label, "underlined");
win.add(label);
@manumaticx
Copy link
Author

It only works on iOS if I set the attributedString at creation-time of the label:

var label = Ti.UI.createLabel({
    text: 'This is a label with an underlined word in its text.',
    attributedString: attr
});

But _label.setAttributedString(attr); seems to be ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment