Tuesday 24 February 2015

Underline in Ti.UI.Label

index.js
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)
Reference

2 comments:

  1. https://sunfishempire.wordpress.com/2014/05/06/displaying-clickable-text-across-platforms-in-titanium/

    ReplyDelete
  2. if (Ti.Platform.name === 'iPhone OS') {
    _label.attributedString = {};
    _label.attributedString = Titanium.UI.createAttributedString({
    text:_word,
    attributes:[{
    type : Titanium.UI.ATTRIBUTE_UNDERLINES_STYLE,
    range : [0,_word.length],
    value : Titanium.UI.ATTRIBUTE_UNDERLINE_STYLE_SINGLE
    }]
    });
    }

    ReplyDelete