Digital Transformation

How to change the color of links in Attributed Strings

Since Titanium 3.2 you can use Attributed Strings on iOS and in 4.0 we added support for Android. They are a great alternative for using heavy WebViews to display formatted text.

Attributed Strings can also include links. By listening to the link event of a label you can handle the link, for example opening it in a SafariDialog or via Ti.Platform.openURL().

Overriding the the default style

Both platforms apply a default color to links and until Titanium 5.2.1 you couldn’t override that. Let me show you how in the following sample:

aslinks

Before

Let’s start out with a Window in vertical layout that uses a helper method to create two identical labels. The helper uses an attributed string with a single link in it. It also adds a listener so we can actually open the link when the user taps on it.

var win = Ti.UI.createWindow({
    layout: 'vertical'
});
win.add(createLabel());
var lbl = createLabel();
// colorLinks(lbl.attributedString);
win.add(lbl);
win.open();
function createLabel() {
    var label = Ti.UI.createLabel({
        top: 50,
        attributedString: Ti.UI.createAttributedString({
            text: 'Check out the Appcelerator Developer Portal',
            attributes: [{
                type: Ti.UI.ATTRIBUTE_LINK,
                value: 'https://developer.appcelerator.com',
                range: [14, 29]
            }]
        })
    });
    label.addEventListener('link', function(e) {
        Ti.Platform.openURL(e.url);
    });
    return label;
}

After

Now we introduce another helper that we can pass any attributed string to color the links to match our theme. We simply loop through the attributes and when we run into a link we add two more attributes to that same range. These use ATTRIBUTE_FOREGROUND_COLOR and ATTRIBUTE_UNDERLINE_COLOR to override the default color for both the main text and the underline.

function colorLinks(as) {
    var color = '#CD1625';
    as.attributes.forEach(function(attribute) {
        if (attribute.type === Ti.UI.ATTRIBUTE_LINK) {
            as.addAttribute({
                type: Ti.UI.ATTRIBUTE_FOREGROUND_COLOR,
                value: color,
                range: attribute.range
            });
            as.addAttribute({
                type: Ti.UI.ATTRIBUTE_UNDERLINE_COLOR,
                value: color,
                range: attribute.range
            });
        }
    });
    return as;
}

And that’s it! Simply wrap your attributed strings with this helper and all your links will display in the desired color. Note that in the above example the return as; isn’t required, but by adding that you can use the helper to directly wrap any call to Ti.UI.createAttributedString() as well.

Code Strong! ?